在开发中会常遇到xml数据序列化和反序列化,这里我们介绍go语言处理xml数据。 encoding/xml 包实现了一个简单的xml 1.0解析器,可以理解xml名称空间。
读取xml
示例:
package main
import (
"encoding/xml"
"fmt"
)
type Note struct {
XMLName xml.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 := `<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tony</to>
<from>jack</from>
<heading>title</heading>
<body>love you</body>
<files flag="true">
<user>zhang</user>
<user>li</user>
</files>
</note>`
note := Note{}
err := xml.Unmarshal([]byte(xmlDoc), ¬e)
if err != nil {
fmt.Println(err.Error())
} else {
fmt.Println(note)
}
}
读取递归数据xml
package main
import (
"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 := `<?xml version="1.0" encoding="UTF-8"?>
<list>
<name>zhang</name>
<list>
<name>li</name>
</list>
</list>`
list := ListItem{}
err := xml.Unmarshal([]byte(xmlDoc), &list)
if err != nil {
fmt.Println(err.Error())
} else {
fmt.Println(list)
}
}
写入xml
示例:
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
)
type Note struct {
XMLName xml.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)
if err!=nil{
fmt.Println(err)
}
fmt.Println(string(xmlContent))
//写入demo.xml
err=ioutil.WriteFile("demo.xml", xmlContent, 0666)
if err!=nil{
fmt.Println(err)
}
}
###写入递归数据
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
)
type ListItem struct {
XMLName xml.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)
if err!=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
|