encoding/xml的使用
Marshal序列化/Unmarshal反序列化
1.Marshal序列化:將結構體序列化成的[]byte
type Person struct {
XMLName xml.Name `xml:"person"` //這個代表xml的根元素名為 person
Name string `xml:"name"` //名為name的子節(jié)點
Age int32 `xml:"age"` //名為age的子節(jié)點
}
//marshal:將結構體編碼成xml格式的[]byte
func testXmlMarsher(){
p :=Person{
Name: "huige",
Age: 20,
}
//編碼成xml無縮進
b1 ,_ := xml.Marshal(p)
fmt.Println("b1:=",string(b1))
//編碼成xml有縮進
b2,_ := xml.MarshalIndent(p," "," ")
fmt.Println("b2:=",string(b2))
}
2.Unmarshal反序列化:一般用于將xml文件的數據反序列化到某個struct中
//Unmarshal:將xml形式的[]byte解碼到一個結構體中
func testXmlUnmarsher(){
b := ` <person>
<name>huige</name>
<age>20</age>
</person>`
data :=[]byte(b)
var person Person
xml.Unmarshal(data,&person)
fmt.Printf("person: %v\n", person)
}
//使用ioutil快速讀取xml文件data,使用Unmarshal反序列化data到struct中庇楞,
func ReadXmlFile(){
data,_:=ioutil.ReadFile("a.xml")
var person Person
xml.Unmarshal(data,&person)
fmt.Println("person:=",person)
}
Decode編碼/Encode解碼
寫xml文件溯街。
func WriteXml(){
p :=Person{
Name: "huige",
Age: 20,
}
fd,_:=os.OpenFile("my.xml",os.O_CREATE|os.O_RDWR,0777)
encoder := xml.NewEncoder(fd) //創(chuàng)建一個encoder
encoder.Encode(p) //將結體數據以xml形式保存到文件中
}
讀取層級比較多的xml的栗子
假如我們有一個如下xml:
<Config>
<account>root</account>
<password>root</password>
<mysql>game</mysql>
<address>127.0.0.1</address>
<cmd>
<data>
<seq>0</seq>
<creator>test</creator>
<type>2</type>
<cmdstr>CmdToForbidRegisterRole 0</cmdstr>
</data>
</cmd>
</Config>
我們應該如何定義結構體呢除嘹?正確應該是一個一個父標簽一個結構體。
根據上面xml我們定義結構體如下:
type Route struct {
Cmdlist []Cmd `xml:"data"`
}
type Cmd struct {
Index int32 `xml:"seq"`
Type int32 `xml:"type"`
Creator string `xml:"creator"`
CmdStr string `xml:"cmdstr"`
}
type Command struct {
XMLName xml.Name `xml:"Config"`
Account string `xml:"account"`
Password string `xml:"password"`
DBName string `xml:"mysql"`
Address string `xml:"address"`
CmdRoute Route `xml:"cmd"`
}
第一層父標簽Config我們對應Command結構體吝秕,第二層父標簽cmd我們定義Route結構體瘫析,第三個層ata父標簽我們定義Cmd結構體佛寿。這樣我們只要層層嵌套,就能把xml反序列化到Comand對象中何暇。
注意
1.xml根節(jié)點需要使用XMLName xml.Name xml:"Config"
指明
2.結構體字段需要大寫陶夜,否則反序列化報錯。
3.如果是整數請確定使用int32或者int64裆站,不要使用int.