Go语言XML生成和解析
Posted 跳动的代码
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Go语言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)
}
以上是关于Go语言XML生成和解析的主要内容,如果未能解决你的问题,请参考以下文章
2022-04-06:go中proto文件能跨平台,那是因为能生成不同语言的代码,做框架开发用protoc+插件生成代码是不合适的,需要解析,请问如何解析?