golang 读取XML配置文件

XML配置文件

解析xml使用”encoding/xml”包

1
2
3
4
5
6
7
8
9
10
11
<config>
<smtpServer>smtp.163.com</smtpServer>
<smtpPort>25</smtpPort>
<sender>user@163.com</sender>
<senderPasswd>123456</senderPasswd>
<receivers flag="true">
<age>29</age>
<user>roddy@qq.com</user>
<user>test1@qq.com</user>
</receivers>
</config>

解析

xml.Unmarshal()

1
2
3
4
5
6
7
8
9
10
11
data, err := ioutil.ReadAll(file)
if err != nil {
fmt.Printf("读取文件失败: %v", err)
return
}
v := ConfigXML{}
err = xml.Unmarshal(data, &v)
if err != nil {
fmt.Printf("解析XML失败: %v", err)
return
}

实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main

import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
)

type SReceivers struct {
Flag string `xml:"flag,attr"` // 读取flag属性
User []string `xml:"user"` // 读取user数组
}

type ConfigXML struct {

XMLName xml.Name `xml:"config"` // 指定最外层的标签为config
SmtpServer string `xml:"smtpServer"` // 读取smtpServer配置项,并将结果保存到SmtpServer变量中
SmtpPort int `xml:"smtpPort"`
Sender string `xml:"sender"`
SenderPasswd string `xml:"senderPasswd"`
Receivers SReceivers `xml:"receivers"` // 读取receivers标签下的内容,以结构方式获取
}



func main(){
file, err := os.Open("config.xml") // For read access.
if err != nil {
fmt.Printf("配置文件错误: %v", err)
return
}
defer file.Close()
data, err := ioutil.ReadAll(file)
if err != nil {
fmt.Printf("读取文件失败: %v", err)
return
}
v := ConfigXML{}
err = xml.Unmarshal(data, &v)
if err != nil {
fmt.Printf("解析XML失败: %v", err)
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)
for i,element := range v.Receivers.User {
fmt.Println(i,element)
}
}