XML data serialization and deserialization are often encountered in development. Here we introduce the go language to process XML data.
The encoding/xml package implements a simple xml 1.0 parser that understands the xml namespace.
read xml
Example:
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)
}
}
read recursive data 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)
}
}
write to xml
Example:
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)
}
}
write recursive data
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)
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。