问题描述
我正在使用的一些 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
", 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 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!