英文:
How to unmarshal XML attributes with colons?
问题
我可以帮你翻译这段代码。以下是翻译的结果:
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"` // 这个可以工作
XlinkHref string `xml:"xlink:href,attr"` // 这个无法工作
}
type Group struct {
A Anchor `xml:"a"`
}
func main() {
group := Group{}
_ = xml.Unmarshal([]byte(data), &group)
fmt.Printf("%#v\n", group.A)
}
这些属性名在语法上是合法的,但是在使用encoding/xml
包的Unmarshal
函数时,无法提取xlink:href
属性。
英文:
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.
答案1
得分: 15
你的示例片段不太正确,因为它没有为 xlink:
前缀绑定一个 XML 命名空间。你可能想要的是:
<g xmlns:xlink="http://www.w3.org/1999/xlink">
<a xlink:href="http://example.com" data-bind="121">lala</a>
</g>
你可以使用命名空间 URL 来解组这个属性:
XlinkHref string `xml:"http://www.w3.org/1999/xlink href,attr"`
这里 是一个修复了命名空间问题的示例程序的更新副本。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论