操作系统: CentOS 6.9_x64
go语言版本: 1.8.3
问题描述
现有一个自动报障程序,如果服务出错会自动给指定人发送邮件,配置文件内容如下(default.xml):
@H_404_12@<?xml version="1.0" encoding="UTF-8"@H_404_12@?> @H_404_12@<config@H_404_12@> @H_404_12@<smtpServer@H_404_12@>smtp.163.com@H_404_12@</smtpServer@H_404_12@> @H_404_12@<smtpPort@H_404_12@>25@H_404_12@</smtpPort@H_404_12@> @H_404_12@<sender@H_404_12@>user@163.com@H_404_12@</sender@H_404_12@> @H_404_12@<senderPasswd@H_404_12@>123456@H_404_12@</senderPasswd@H_404_12@> @H_404_12@<receivers flag@H_404_12@="true"@H_404_12@> @H_404_12@<user@H_404_12@>Mike_Zhang@live.com@H_404_12@</user@H_404_12@> @H_404_12@<user@H_404_12@>test1@qq.com@H_404_12@</user@H_404_12@> @H_404_12@</receivers@H_404_12@> @H_404_12@</config@H_404_12@>
该配置以config为root标签,有xml text部分(比如smtpServer标签)、嵌套xml(receivers标签)、有xml attribute部分(receivers标签的flag)、类似数组的多行配置(user标签), 数据类型有字符串和数字两种类型。
解决方案
package main import ( "encoding/xml" "fmt" "io/IoUtil" "os" ) type SConfig @H_404_12@struct { XMLName xml.Name `xml:"config"` // 指定最外层的标签为config SmtpServer @H_404_12@string `xml:"smtpServer"` // 读取smtpServer配置项,并将结果保存到SmtpServer变量中 SmtpPort @H_404_12@int `xml:"smtpPort"` Sender @H_404_12@string `xml:"sender"` SenderPasswd @H_404_12@string `xml:"senderPasswd"` Receivers SReceivers `xml:"receivers"` // 读取receivers标签下的内容,以结构方式获取 } type SReceivers @H_404_12@struct { Flag @H_404_12@string `xml:"flag,attr"` // 读取flag属性 User []@H_404_12@string `xml:"user"` // 读取user数组 } func main() { file,err := os.Open("default.xml") // For read access. @H_404_12@if err != nil { fmt.Printf("error: %v",err) @H_404_12@return } defer file.Close() data,err := IoUtil.ReadAll(file) @H_404_12@if err != nil { fmt.Printf("error: %v",err) @H_404_12@return } v := SConfig{} err = xml.Unmarshal(data,&v) @H_404_12@if err != nil { fmt.Printf("error: %v",err) @H_404_12@return } fmt.Println(v) fmt.Println("SmtpServer : ",v.SmtpServer) fmt.Println("SmtpPort : ",v.SmtpPort) fmt.Println("Sender : ",v.Sender) fmt.Println("SenderPasswd : ",v.SenderPasswd) fmt.Println("Receivers.Flag : ",v.Receivers.Flag) @H_404_12@for i,element := range v.Receivers.User { fmt.Println(i,element) } }
运行效果:
[root@local t1]# @H_404_12@ls default.xml xmlCnfTest1.go [root@local t1]# go run xmlCnfTest1.go {{ config} smtp.163.com 25 user@163.com 123456 {@H_404_12@true [Mike_Zhang@live.com test1@qq.com]}} SmtpServer : smtp.163.com SmtpPort : 25 Sender : user@163.com SenderPasswd : 123456 Receivers.Flag : @H_404_12@true 0 Mike_Zhang@live.com 1 test1@qq.com [root@local t1]#
讨论
如果需要直接从字符串解析xml配置,可将如下语句中的data替换即可:
err = xml.Unmarshal(data,&v)
比如:
err = xml.Unmarshal([]@H_404_12@byte(ConfigContent),&v) // ConfigContent为xml字符串
好,就这些了,希望对你有帮助。
本文github地址:
https://github.com/mike-zhang/mikeBlogEssays/blob/master/2017/20170610_使用go解析xml.rst
欢迎补充