英文:
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 = `<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
}
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:"id,attr"` // A_ID
Name struct {
Id string `xml:"id,attr"` // B_ID
} `xml:"B"`
}
Or maybe even better - define separate B struct:
type A struct {
Id string `xml:"id,attr"` // A_ID
Name B `xml:"B"`
}
type B struct {
Id string `xml:"id,attr"` // B_ID
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论