Go XML解组节点N的属性X

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

Go XML Unmarshalling attribute X of node N

问题

我想将特定节点N的属性X的值解组到一个结构字段中。类似这样的代码:

var data = `<A id="A_ID">
<B id="B_ID">Something</B>
</A>`

type A struct {
    Id   string `xml:"id,attr"`     // A_ID
    Name string `xml:"B.id,attr"`   // B_ID
}

根据我所了解,Go语言目前不支持这样的操作。我是正确的吗?还是我漏掉了什么?

英文:

I would like to unmarshall the value of an attribute X of specific node N to a struct field. Something like this:

var data = `&lt;A id=&quot;A_ID&quot;&gt;
&lt;B id=&quot;B_ID&quot;&gt;Something&lt;/B&gt;
&lt;/A&gt;
`

type A struct {
	Id   string `xml:&quot;id,attr&quot;` // A_ID
	Name string `xml:&quot;B.id,attr&quot;` // B_ID
}

http://play.golang.org/p/U6daYJWVUX

As far as I was able to check this is not supported by Go. Am I correct, or am I missing something here?

答案1

得分: 2

在你的问题中,你没有提到B。我猜你需要将其属性解析为A.Name?如果是这样的话,你可以将你的A结构体改为以下形式:

type A struct {
    Id string `xml:"id,attr"` // A_ID
    Name struct {
        Id string `xml:"id,attr"` // B_ID
    } `xml:"B"`
}

或者更好的方式是定义一个单独的B结构体:

type A struct {
    Id string `xml:"id,attr"` // A_ID
    Name B `xml:"B"`
}

type B struct {
    Id string `xml:"id,attr"` // B_ID
}
英文:

In your question you are not mentioning B. I'm guessing that you need to unmarshal its attr into A.Name? If so - you could change your A struct to something like this:

type A struct {
    Id string `xml:&quot;id,attr&quot;` // A_ID
	Name  struct {
	    Id string `xml:&quot;id,attr&quot;` // B_ID
    } `xml:&quot;B&quot;`
}

Or maybe even better - define separate B struct:

type A struct {
    Id string `xml:&quot;id,attr&quot;` // A_ID
    Name  B `xml:&quot;B&quot;`
}

type B struct {
	Id string `xml:&quot;id,attr&quot;` // B_ID
}

huangapple
  • 本文由 发表于 2014年12月10日 23:13:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/27404456.html
匿名

发表评论

匿名网友

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

确定