英文:
How to build a three layers xml in Go
问题
我已经做了足够的功课,知道如何构建一个单层的 XML,就像这样:
<name>aaa</name><id>233</id>
但是我对如何在 Go 中构建三层或更多层的 XML 感到困惑。
<Person>
<Id>233</Id>
<Information>
<name>aaa</name>
</Information>
</Person>
我知道我可以使用 Person.Id = 233
,但我无法做更多的操作。
需要帮助,我是新手,非常感谢!
英文:
I`ve do enough homework that i know how to build a one laver xml just like
<name>aaa</name><id>233</id>
But im puzzled by how to build a three or more layers xml in go now.
<Person>
<Id>233</Id>
<Information>
<name>aaa</name>
</Information>
</Person>
I know i can use Person.Id = 233 but i cant do more.
Need help, im a new, thks a lot!
答案1
得分: 0
你只需要嵌套结构体即可。你可以无限嵌套,例如Info
可以再内部包含另一个结构体。
type Person struct {
Id int
Information Info
}
type Info struct {
Name string `xml:"name"`
}
func main() {
p := &Person{
Id: 233,
Information: Info{
Name: "aaa",
},
}
dat, err := xml.Marshal(p)
if err != nil {
return
}
fmt.Println(string(dat))
}
如需进一步了解,请参考文档 https://godoc.org/encoding/xml#Marshal 和其中提供的示例:https://godoc.org/encoding/xml?play=MarshalIndent
英文:
You just have to nest the structs. You can go as deep as you want e.g. Info
could have yet another struct inside it.
https://play.golang.org/p/pADEJXj8En
type Person struct {
Id int
Information Info
}
type Info struct {
Name string `xml:"name"`
}
func main() {
p := &Person{
Id: 233,
Information: Info {
Name: "aaa",
},
}
dat, err := xml.Marshal(p)
if err != nil {
return
}
fmt.Println(string(dat))
}
For further information, refer to the documentation https://godoc.org/encoding/xml#Marshal and the example given there: https://godoc.org/encoding/xml?play=MarshalIndent
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论