前言
Go语言通过XML文件序列化和反序列化
Go对象转换为XML格式字符串
引入依赖
1 2 3
| import ( "encoding/xml" )
|
创建结构体
无嵌套关系
omitempty
:如果属性值为空,则生成XML时忽略该字段
xml:"-"
:无论是否为空,生成XML时都强制忽略
attr
:指定改字段不是标签而是属性,XML属性的名是结构体属性名Key4,XML属性值是结构体的属性值
1 2 3 4 5 6
| type Persion struct { Key1 string `xml:"key1"` Key2 string `xml:"key2,omitempty"` Key3 string `xml:"-"` Key4 string `xml:"key4,attr"` }
|
有嵌套关系
通过结构体嵌套实现
1 2 3 4 5 6 7 8
| type Person struct { Parent Parent `xml:"parent"` }
type Parent struct { Father string `xml:"father"` Mother string `xml:"mother"` }
|
通过属性的Tag实现
1 2 3 4
| type Person struct { Father string `xml:"parent>father"` Mother string `xml:"parent>mother"` }
|
序列化为XML格式字符串
无缩进无换行
1 2 3
| person := Person{Key: "value"}
data, err := xml.Marshal(person)
|
指定缩进字符并自动换行
第2个参数:每行前缀
第3个参数:缩进时的字符
1 2 3
| person := Person{Key: "value"}
data, err := xml.MarshalIndent(persion, "", " ")
|
存储XML格式字符串为XML文件
<filename>
:文件名
1
| ioutil.WriteFile("<filename>.xml", data, 0644)
|
反序列化
读取XML文件为XML格式字符数组
<filename>
:文件名
1
| content, err := ioutil.ReadFile("filename.xml")
|
反序列化XML格式字符数组为结构体
1 2 3
| person := Person{}
xml.Unmarshal(content, person)
|
完成
参考文献
哔哩哔哩——禾木课堂