gol*_*kou 1 xml struct go unmarshalling slice
根据下面的链接,我们可以使用>或其他结构从嵌套的xml中获取数据。
但是,在不使用这种结束标记的情况下,它不起作用。
码:
package main
import (
"fmt"
"encoding/xml"
)
func main() {
container := Parent{}
err := xml.Unmarshal([]byte(xml_data), &container)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(container)
}
}
var xml_data = `<Parent>
<Val>Hello</Val>
<Child Val="Hello"/>
<Child Val="Hello"/>
<Child Val="Hello"/>
</Parent>`
type Parent struct {
Val string
Children Children
}
type Children struct {
Child []Child
}
type Child struct {
Val string
}
Run Code Online (Sandbox Code Playgroud)
结果:
{Hello {[]}}
Run Code Online (Sandbox Code Playgroud)
有什么办法吗?
<Child>在XML中,它是的“子级” Parent,因此要摆脱Children包装器结构,切片应为的字段Parent。此外,中的值<Child>都在属性中,因此您必须使用该,attr选项。
工作模式:
type Parent struct {
Val string
Child []Child
}
type Child struct {
Val string `xml:",attr"`
}
Run Code Online (Sandbox Code Playgroud)
这将输出(在Go Playground上尝试):
{Hello [{Hello} {Hello} {Hello}]}
Run Code Online (Sandbox Code Playgroud)