如何在Go中构建一个三层的XML结构?

huangapple go评论182阅读模式
英文:

How to build a three layers xml in Go

问题

我已经做了足够的功课,知道如何构建一个单层的 XML,就像这样:

  1. <name>aaa</name><id>233</id>

但是我对如何在 Go 中构建三层或更多层的 XML 感到困惑。

  1. <Person>
  2. <Id>233</Id>
  3. <Information>
  4. <name>aaa</name>
  5. </Information>
  6. </Person>

我知道我可以使用 Person.Id = 233,但我无法做更多的操作。
需要帮助,我是新手,非常感谢!

英文:

I`ve do enough homework that i know how to build a one laver xml just like

  1. &lt;name&gt;aaa&lt;/name&gt;&lt;id&gt;233&lt;/id&gt;

But im puzzled by how to build a three or more layers xml in go now.

  1. &lt;Person&gt;
  2. &lt;Id&gt;233&lt;/Id&gt;
  3. &lt;Information&gt;
  4. &lt;name&gt;aaa&lt;/name&gt;
  5. &lt;/Information&gt;
  6. &lt;/Person&gt;

I know i can use Person.Id = 233 but i cant do more.
Need help, im a new, thks a lot!

答案1

得分: 0

你只需要嵌套结构体即可。你可以无限嵌套,例如Info可以再内部包含另一个结构体。

  1. type Person struct {
  2. Id int
  3. Information Info
  4. }
  5. type Info struct {
  6. Name string `xml:"name"`
  7. }
  8. func main() {
  9. p := &Person{
  10. Id: 233,
  11. Information: Info{
  12. Name: "aaa",
  13. },
  14. }
  15. dat, err := xml.Marshal(p)
  16. if err != nil {
  17. return
  18. }
  19. fmt.Println(string(dat))
  20. }

如需进一步了解,请参考文档 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

  1. type Person struct {
  2. Id int
  3. Information Info
  4. }
  5. type Info struct {
  6. Name string `xml:&quot;name&quot;`
  7. }
  8. func main() {
  9. p := &amp;Person{
  10. Id: 233,
  11. Information: Info {
  12. Name: &quot;aaa&quot;,
  13. },
  14. }
  15. dat, err := xml.Marshal(p)
  16. if err != nil {
  17. return
  18. }
  19. fmt.Println(string(dat))
  20. }

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

huangapple
  • 本文由 发表于 2017年8月29日 23:40:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/45943254.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定