Reputation: 7908
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:
http://play.golang.org/p/LpI2vKFpNE
Upvotes: 2
Views: 85
Reputation: 3237
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
Upvotes: 1