在开发中会常遇到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"`
}
func main() {
//读取xml文件到缓存中,返回[]byte
//XmlParam, err := ioutil.ReadFile("test.xml")
//if err != nil {
//fmt.Println("xml文件读取失败!")
//return
//}
//fmt.Println(string(XmlParam))
xmlDoc := `<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tony</to>
<from>jack</from>
<heading>title</heading>
<body>love you</body>
</note>`
note := Note{}
err := xml.Unmarshal([]byte(xmlDoc), ¬e)
if err != nil {
fmt.Println(err.Error())
} else {
fmt.Println(note.XMLName)
}
}
写入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"`
}
func main() {
note:=Note{
To: "tony",
From: "jack",
Heading: "title",
Body: "love you",
}
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)
}
}
links