在開發中會常遇到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)
}
}