英文:
Context-agnostic XML struct tagging
问题
我想要能够给我的结构体添加标签,而不需要知道它将嵌套到 XML 文档的哪个级别。换句话说,我希望能够这样写:
type Elem struct {
Datum string `xml:"datum"`
}
并且它可以同时适用于以下两种情况:
<elem>
<datum>Hello</datum>
</elem>
和
<list>
<elem>
<datum>Hello</datum>
</elem>
</list>
然而,为了使后一个示例(尝试解码为 []Elem
)正常工作,我需要使用标签 xml:"elem>datum"
,这会导致第一个示例解码错误。有没有办法在不知道结构体将如何嵌入的情况下定义 XML 标签?在这里可以看到一个简单的示例:
http://play.golang.org/p/LpI2vKFpNE
英文:
I would like to be able to tag my struct without it needing to know what level it will be nested into an XML document. In other words, I want to be able to write:
type Elem struct {
Datum string `xml:"datum"`
}
And have it work for both
<elem>
<datum>Hello</datum>
</elem>
And
<list>
<elem>
<datum>Hello</datum>
</elem>
</list>
However, in order for the latter example to work (when attempting to decode into a []Elem
), I need to use the tag xml:"elem>datum"
, which decodes incorrectly for the first example. Is there a way for me to define an XML tag without knowing how the struct will be embedded? See here for a simple example:
答案1
得分: 1
一种解决方法是使用匿名结构体:
func Test2_DecodeList() {
xmlData := "<list><elem><datum>Hello</datum></elem></list>"
var list struct {
Elems []Elem `xml:"elem"`
}
if err := xml.Unmarshal([]byte(xmlData), &list); err != nil {
fatal("Test2:", err)
}
if err := expectEq(1, len(list.Elems)); err != nil {
fatal("Test2:", err)
}
if err := expectEq("Hello", list.Elems[0].Datum); err != nil {
fatal("Test2:", err)
}
}
示例:http://play.golang.org/p/UyYoyGgL_K
英文:
One way to solve this is through the use of an anonymous struct:
func Test2_DecodeList() {
xmlData := "<list><elem><datum>Hello</datum></elem></list>"
var list struct {
Elems []Elem `xml:"elem"`
}
if err := xml.Unmarshal([]byte(xmlData), &list); err != nil {
fatal("Test2:", err)
}
if err := expectEq(1, len(list.Elems)); err != nil {
fatal("Test2:", err)
}
if err := expectEq("Hello", list.Elems[0].Datum); err != nil {
fatal("Test2:", err)
}
}
Example: http://play.golang.org/p/UyYoyGgL_K
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论