我想使用不同的类型根据父节点的 name 属性来解组子节点的 XML 内容。
在下面的示例中,我有 2 个具有属性“apple”和“peach”的子节点。我想Apple
在属性为 时"apple"
使用Peach
type "peach"
。基本上Apple
并且Peach
有非常不同的结构,所以这就是场景。我将如何实现这一目标或建议的方法是什么?
这是解决问题的基本设置的游乐场。
<element>
<node name="apple">
<apple>
<color>red<color>
</apple>
</node>
<node name="peach">
<peach>
<size>medium</size>
</peach>
</node>
</element>
var x = `...` // xml
type Element struct {
Nodes []struct{
Name string `xml:"name,attr"`
} `xml:"node"`
Apple Apple
Peach Peach
}
type Apple struct { // use this struct if name is "apple"
Color string
}
type Peach struct { // use this struct if name is "peach"
Size string
}
func main() {
e := Element{}
err := xml.Unmarshal([]byte(x), &e)
if err != nil {
panic(err)
}
fmt.Println(e.Apple.Color)
fmt.Println(e.Peach.Size
}
桃花长相依
相关分类