如何解析带有冒号的 XML 属性?

huangapple go评论82阅读模式
英文:

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:

&lt;g&gt;
  &lt;a xlink:href=&quot;http://example.com&quot; data-bind=&quot;121&quot;&gt;...&lt;/a&gt;
&lt;/g&gt;

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 (
	&quot;encoding/xml&quot;
	&quot;fmt&quot;
)

var data = `
&lt;g&gt;
    &lt;a xlink:href=&quot;http://example.com&quot; data-bind=&quot;121&quot;&gt;lala&lt;/a&gt;
&lt;/g&gt;
`

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

type Group struct {
	A Anchor `xml:&quot;a&quot;`
}

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

	fmt.Printf(&quot;%#v\n&quot;, group.A)
}

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

答案1

得分: 15

你的示例片段不太正确,因为它没有为 xlink: 前缀绑定一个 XML 命名空间。你可能想要的是:

&lt;g xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot;&gt;
  &lt;a xlink:href=&quot;http://example.com&quot; data-bind=&quot;121&quot;&gt;lala&lt;/a&gt;
&lt;/g&gt;

你可以使用命名空间 URL 来解组这个属性:

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

这里 是一个修复了命名空间问题的示例程序的更新副本。

英文:

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:

&lt;g xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot;&gt;
  &lt;a xlink:href=&quot;http://example.com&quot; data-bind=&quot;121&quot;&gt;lala&lt;/a&gt;
&lt;/g&gt;

You can unmarshal this attribute using the namespace URL:

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

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

huangapple
  • 本文由 发表于 2013年9月21日 23:25:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/18934327.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定