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

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

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

&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.

&lt;Person&gt;
    &lt;Id&gt;233&lt;/Id&gt;
    &lt;Information&gt;
        &lt;name&gt;aaa&lt;/name&gt;
    &lt;/Information&gt;
&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可以再内部包含另一个结构体。

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:&quot;name&quot;`
}

func main() {
	p := &amp;Person{
		Id: 233,
		Information: Info {
			Name: &quot;aaa&quot;,
		},
	}
	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

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:

确定