XML是指可扩展标记语言(eXtensible MarkupLanguage),它是一种标记语言。它被设计的宗旨是描述数据(XML),而非显示数据(HTML)。
Go语言中,我们用xml包的Unmarshal来解析XML文档,MarshalIndent来生成XML文档。
<?xml version="1.0" encoding="utf-8"?>
<devices version="1">
<device>
<deviceName>智能摄像头</deviceName>
<deviceCode>100000000001</deviceCode>
<deviceDate>2020-03-01</deviceDate>
</device>
<device>
<deviceName>智能挖掘机</deviceName>
<deviceCode>200000000001</deviceCode>
<deviceDate>2020-03-01</deviceDate>
</device>
</devices>
type Device struct {
XMLName xml.Name `xml:"devices"`
Version string `xml:"version,attr"`
Device []DeviceNode `xml:"device"`
Description string `xml:",innerxml"`
}
type DeviceNode struct {
XMLName xml.Name `xml:"device"`
DeviceName string `xml:"deviceName"`
DeviceCode string `xml:"deviceCode"`
DeviceDate string `xml:"deviceDate"`
}
-
-
"name,attr",以name作为属性名,字段值作为输出这个XML元素的属性
-
",attr",以这个结构体struct的字段名作为属性名输出XML元素的属性,name默认是字段名
-
",chardata",输出XML元素为character data而非element。
-
",innerxml",原样输出,不进行常规的编码过程
-
",comment",作为XML注释来输出,不进行编码过程,字段中不能有“--”字符串
-
"omitempty",若字段值为空、那么字段不会被输出到XML,空值有:false、0、nil指针,nil接口,任意长度为0的Slice、数组结构、Map结构或者string
var o = Device{}
o.Device = append(o.Device, DeviceNode{
DeviceName: "电脑",
DeviceCode: "300000000001",
DeviceDate: "2020-01-01",
})
o.Device = append(o.Device, DeviceNode{
DeviceName: "游戏机",
DeviceCode: "400000000001",
DeviceDate: "2020-01-02",
})
o.Device = append(o.Device, DeviceNode{
DeviceName: "苹果手机",
DeviceCode: "500000000001",
DeviceDate: "2020-01-03",
})
resXML, err := xml.MarshalIndent(o, " ", " ")
if err != nil {
fmt.Printf("marshal xml err :%v\n", err)
return
}
_, _ = os.Stdout.Write([]byte(xml.Header))
_, _ = os.Stdout.Write(resXML)
file := "./device.xml"
fd, err := os.Open(file)
if err != nil {
fmt.Printf("open file err : %v\n", err)
return
}
defer fd.Close()
fileContent, err := ioutil.ReadAll(fd)
if err != nil {
fmt.Printf("read file err : %v\n", err)
return
}
var device = Device{}
err = xml.Unmarshal(fileContent, &device)
if err != nil {
fmt.Printf("unmarshal err : %v\n", err)
return
}
for idx, node := range device.Device {
fmt.Printf("序号:[%d],设备名:[%s],设备编码:[%s],设备日期:[%s]\n",
idx, node.DeviceName, node.DeviceCode, node.DeviceDate)
}