【Go xml文件处理】在开发中会常遇到xml数据序列化和反序列化,这里我们介绍go语言处理xml数据。
encoding/xml 包实现了一个简单的xml 1.0解析器,可以理解xml名称空间。
读取xml
示例:
package mainimport (
"encoding/xml"
"fmt"
)type Note struct {
XMLNamexml.Name `xml:"note"`
To string `xml:"to"`
From string `xml:"from"`
Heading string `xml:"heading"`
Body string `xml:"body"`
Files FilesArr `xml:"files"`
}
type FilesArr struct {
Flag string `xml:"flag,attr"` // 读取flag属性
User []string `xml:"user"` // 读取user数组
}
func main(){
//读取xml文件到缓存中,返回[]byte
//xmlDoc, err := ioutil.ReadFile("test.xml")
//if err != nil {
//fmt.Println("xml文件读取失败!")
//return
//}
//fmt.Println(string(xmlDoc))
xmlDoc := `
Tony
jack
title
love you
zhang
li
`
note := Note{}
err := xml.Unmarshal([]byte(xmlDoc), ¬e)
if err != nil {
fmt.Println(err.Error())
} else {
fmt.Println(note)
}
}
读取递归数据xml
package mainimport (
"encoding/xml"
"fmt"
)
type ListItem struct {
Name string `xml:"name"`
List []ListItem `xml:"list"`
}func main(){
//读取xml文件到缓存中,返回[]byte
//xmlDoc, err := ioutil.ReadFile("test.xml")
//if err != nil {
//fmt.Println("xml文件读取失败!")
//return
//}
//fmt.Println(string(xmlDoc))
xmlDoc := `
zhang
li
`
list := ListItem{}
err := xml.Unmarshal([]byte(xmlDoc), &list)
if err != nil {
fmt.Println(err.Error())
} else {
fmt.Println(list)
}
}
写入xml
示例:
package mainimport (
"encoding/xml"
"fmt"
"io/ioutil"
)type Note struct {
XMLNamexml.Name `xml:"note"`
To string `xml:"to"`
From string `xml:"from"`
Heading string `xml:"heading"`
Body string `xml:"body"`
Files FilesArr `xml:"files"`
}
type FilesArr struct {
Flag string `xml:"flag,attr"` // 读取flag属性
User []string `xml:"user"` // 读取user数组
}
func main(){
user:=[]string{"zhang","li"}
files:=FilesArr{Flag: "true",User: user}
note:=Note{
To: "tony",
From: "jack",
Heading: "title",
Body: "love you",
Files:files,
}
xmlContent,err:=xml.Marshal(note)
iferr!=nil{
fmt.Println(err)
}
fmt.Println(string(xmlContent))
//写入demo.xml
err=ioutil.WriteFile("demo.xml", xmlContent, 0666)
if err!=nil{
fmt.Println(err)
}
}
写入递归数据
package mainimport (
"encoding/xml"
"fmt"
"io/ioutil"
)type ListItem struct {
XMLNamexml.Name `xml:"list"`
Name string `xml:"name"`
List []ListItem `xml:"list"`
}func main(){
list:=ListItem{Name: "li",List: nil}
lists:=ListItem{Name: "zhang"}
l := make([]ListItem,0)
lists.List=append(l,list)
xmlContent,err:=xml.Marshal(lists)
iferr!=nil{
fmt.Println(err)
}
fmt.Println(string(xmlContent))
//写入demo.xml
err=ioutil.WriteFile("demo.xml", xmlContent, 0666)
if err!=nil{
fmt.Println(err)
}}
links https://studygolang.com/pkgdoc
- 目录