如何用冒号解组XML属性? [英] How to unmarshal XML attributes with colons?
问题描述
我正在使用的某些SVG/XML文件的属性名称中带有破折号和冒号-例如:
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>
我正在尝试使用 golang
的方法来解组这些属性 encoding/xml
包.虽然虚线属性有效,但带有冒号的属性不起作用:
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:
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)
}
这些是看似合法的属性名称;任何想法如何提取 xlink:href
一个?谢谢.
These are seemingly legal attribute names; any idea how to extract the xlink:href
one? thanks.
推荐答案
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>
您可以使用名称空间URL解封此属性:
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.
这篇关于如何用冒号解组XML属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!