本文对 xml 文件进行解析。
概述
某项目涉及到数据传输,我负责运行在工控机的客户端。实际上,工控机已经有了作为“数据传输”角色的程序,已经 worked 了很多年,从工程较多处出现的func_<年份>
来看,年龄不小于已经上小学的李大锤。作为继任者,理应继续发扬,但接手以来,数值传输出现了各种或大或小的问题,涉及到不同位置的服务端,也涉及到不同厂商的第三方的别家的中间件。实在无力再在其上添砖加瓦。作为具体实施者,考虑到技术栈、开发难度和时间,我在会议多次提议后,最终同意使用 Golang 来实现,并以此作为一个新的数据通道,后续择机发挥作用。
在此之前,我自己总结的 Golang 程序框架已经应用到4个项目工程里了,期间积累了大量有用的工具函数,因此开发的基础性工作不多,专注业务即可。但在实际上,还需要考虑和其它业务程序的交互、数据格式、xml配置文件等方面。本文抛开主要业务不谈,单纯考虑兼容性,测试xml配置文件的读取。
测试
Golang 内置了解析 xml 的接口,直接使用即可,不引入外部包。
配置文件config.ini
文件内容:
<!-- xml 测试样例 -->
<?xml version="1.0" encoding="UTF-8" ?>
<config><info><id>000250</id><num>256</num><!-- 小节中有小节 --><person><location>梧州市岑溪市</location><email>li@latelee.cn</email><!-- 代码不解析此段 --><name><first>First</first><last>Last</last></name></person></info><server><filename back="backkkk">/tmp/log.txt</filename><url>http://172.18.18.168:9001/testing</url><!-- 空字段 --><empty></empty><!-- 注释字段,代码中有 --><!-- <time></time> --></server>
</config>
测试代码:
package testimport ("encoding/xml""fmt""io/ioutil""testing"
)var (cfgFile string = "config.xml"
)type XMLConfig_t struct {XMLName xml.Name `xml:"config"` // 最外层的标签 configInfoNode XMLInfo_t `xml:"info"` // 读取 info 标签下的内容ServerNode XMLServer_t `xml:"server"` // 读取 server 标签下的内容
}type XMLInfo_t struct {Id string `xml:"id"`Num string `xml:"num"`PersonNode XMLPerson_t `xml:"person"` // 读取 person 标签下的内容
}type XMLPerson_t struct {Location string `xml:"location"`Email string `xml:"email"`
}type XMLServer_t struct {Filename string `xml:"filename"`Url string `xml:"url"`Empty string `xml:"empty"`Time int `xml:"time"`
}func TestXml(t *testing.T) {fmt.Println("test of xml...")// 读文件xdata, err := ioutil.ReadFile(cfgFile)if err != nil {fmt.Printf("open config file [%v] failed: %v\n", cfgFile, err.Error())return}// 解析var xmlConfig XMLConfig_terr = xml.Unmarshal(xdata, &xmlConfig)if err != nil {fmt.Printf("parse xml error: %v", err.Error())return}fmt.Printf("id: %v location: %v\n", xmlConfig.InfoNode.Id, xmlConfig.InfoNode.PersonNode.Location)fmt.Printf("filename: %v time: %v\n", xmlConfig.ServerNode.Filename, xmlConfig.ServerNode.Time)}
从代码可以看到,xm的解析和json的解析类似,在结构体中通过关键字xml
来判断,如xml层级较深,则相应的结构体亦然,但可以选取所需字段,不一定要全部给出定义。
输出结果:
test of xml...
id: 000250 location: 梧州市岑溪市
filename: /tmp/log.txt time: 0
小结
开发维护代码,一定要考虑兼容性,某些代码或机制可能被认为反常,但可能是从历史教训中得到的宝贵经验,牵一发而动全身。就 Golang 解析 xml 而言,并不是很难,鉴于笔者用到的机会不多,因此不展开测试。