13

Some SVG/XML files I'm working with have dashes and colons in attribute names - for example:

<g>
  <a xlink:href="http://example.com" data-bind="121">...</a>
</g>

I'm trying to figure out how to unmarshal these attributes using golang's encoding/xml package. While the dashed attributes works, the ones with the colon doesn't:

[See here for a live example]

package main

import (
    "encoding/xml"
    "fmt"
)

var data = `
<g>
    <a xlink:href="http://example.com" data-bind="121">lala</a>
</g>
`

type Anchor struct {
    DataBind  int    `xml:"data-bind,attr"`  // this works
    XlinkHref string `xml:"xlink:href,attr"` // this fails
}

type Group struct {
    A Anchor `xml:"a"`
}

func main() {
    group := Group{}
    _ = xml.Unmarshal([]byte(data), &group)

    fmt.Printf("%#v\n", group.A)
}

These are seemingly legal attribute names; any idea how to extract the xlink:href one? thanks.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
sa125
  • 28,121
  • 38
  • 111
  • 153

1 Answers1

15

Your example fragment is not quite correct, since it does not include an XML namespace binding for the xlink: prefix. What you probably want is:

<g xmlns:xlink="http://www.w3.org/1999/xlink">
  <a xlink:href="http://example.com" data-bind="121">lala</a>
</g>

You can unmarshal this attribute using the namespace URL:

XlinkHref string `xml:"http://www.w3.org/1999/xlink href,attr"`

Here is an updated copy of your example program with the namespace fix.

James Henstridge
  • 42,244
  • 6
  • 132
  • 114
  • 1
    Just to add, I had trouble getting attributes prefixed with "xml", like `xml:lang="eng"`, but seems like since xml is default(?) you can just use `\`xml:"lang,attr"\`` as usual. – localhost Feb 27 '15 at 03:19
  • Well, the `xml:` prefix for attributes doesn't actually identify an XML namespace. It was defined before the XML Namespace spec. – James Henstridge Feb 27 '15 at 05:08
  • 1
    An example for what localhost is referring to above, that failing line would change to ``xml:"href,attr"`` .. like so https://play.golang.org/p/30p2ebQMD0 – Michael M Oct 01 '16 at 07:39