per.xml 准备被读取的数据
<persons>
<person name="张三" age="20">
<gender>男</gender>
<interests>
<interest>编程</interest>
<interest>阅读</interest>
</interests>
<salary>3500</salary>
</person>
</persons>
- main.go
xml:”person”:xml中person字段
xml:”name,attr”:xml中name属性
注意:存储字段的变量名首字母必须是大写
package main
import (
"io/ioutil"
"fmt"
"os"
"encoding/xml"
)
type Persons struct {
Person []Person `xml:"person"`
}
type Person struct {
Name string `xml:"name,attr"`
Age string `xml:"age,attr"`
Gender string `xml:"gender"`
Interests Interests `xml:"interests"`
}
type Interests struct {
Interest []string `xml:"interest"`
}
func main() {
//将文件读取成字节数组
content, err := ioutil.ReadFile("per.xml")
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(9)
}
var ps Persons
//反序列化xml
xml.Unmarshal(content, &ps)
fmt.Println(ps.Person[0].Name)
fmt.Println(ps.Person[0].Age)
fmt.Println(ps.Person[0].Gender)
fmt.Println(ps.Person[0].Interests)
fmt.Println(ps.Person[0].Interests.Interest[0])
fmt.Println(ps.Person[0].Interests.Interest[1])
}
结果:
[root@localhost xmlTest]# go build main.go
[root@localhost xmlTest]# ./main
张三
20
男
{[编程 阅读]}
编程
阅读