猿问

如何在 Go 中解组具有多个项目的简单 xml?

我想从以下 xml 中获取一部分人 ([]People):


<file>

    <person>

        <name>John Doe</name>

        <age>18</age>

    </person>

    <person>

        <name>Jane Doe</name>

        <age>20</age>

    </person>

</file>

(所有其他类似问题都过于具体和冗长)


胡说叔叔
浏览 86回答 1
1回答

大话西游666

您需要创建两个结构:一个代表<file>&nbsp;</file>一个用于重复记录<person>&nbsp;</person>请看代码里面的注释:package mainimport (&nbsp; &nbsp; "encoding/xml"&nbsp; &nbsp; "fmt")var sourceXML = []byte(`<file>&nbsp; &nbsp; <person>&nbsp; &nbsp; &nbsp; &nbsp; <name>John Doe</name>&nbsp; &nbsp; &nbsp; &nbsp; <age>18</age>&nbsp; &nbsp; </person>&nbsp; &nbsp; <person>&nbsp; &nbsp; &nbsp; &nbsp; <name>Jane Doe</name>&nbsp; &nbsp; &nbsp; &nbsp; <age>20</age>&nbsp; &nbsp; </person></file>`)// Define a structure for each recordtype Person struct {&nbsp; &nbsp; Name string `xml:"name"`&nbsp; &nbsp; Age&nbsp; int&nbsp; &nbsp; `xml:"age"`}// There needs to be a single struct to unmarshal into// File acts like that one root structtype File struct {&nbsp; &nbsp; People []Person `xml:"person"`}func main() {&nbsp; &nbsp; // Initialize an empty struct&nbsp; &nbsp; var file File&nbsp; &nbsp; err := xml.Unmarshal(sourceXML, &file)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(err)&nbsp; &nbsp; }&nbsp; &nbsp; // file.People returns only the []Person rather than the root&nbsp; &nbsp; // file struct with it's contents&nbsp; &nbsp; fmt.Printf("%+v", file.People)}// output:// [{Name:John Doe Age:18} {Name:Jane Doe Age:20}]编辑。Kaedys 说 File 和 Person 结构也可以嵌套(使用匿名结构),如下所示:type File struct {&nbsp; &nbsp; People []struct {&nbsp; &nbsp; &nbsp; &nbsp; Name string `xml:"name"`&nbsp; &nbsp; &nbsp; &nbsp; Age&nbsp; int&nbsp; &nbsp; `xml:"age"`&nbsp; &nbsp; } `xml:"person"`}
随时随地看视频慕课网APP

相关分类

Go
我要回答