Go語言解析xml格式資料
阿新 • • 發佈:2018-12-24
開發工具:Goland。
xml檔案,解析與json檔案解析非常相似。只是用了不同的包。
比如一個xml檔案,內容如下
<?xml version="1.0" encoding="utf-8"?>
<servers version="1">
<server>
<serverName>Shanghai_VPN</serverName>
<serverIP>127.0.0.1</serverIP>
</server>
<server >
<serverName>Beijing_VPN</serverName>
<serverIP>127.0.0.2</serverIP>
</server>
</servers>
檔案中有4個欄位,servers
、server
、serverName
、serverIP
,所以根據檔案結構,構建兩個結構體,
type server struct {
XMLName xml.Name `xml:"server"`
ServerName string `xml:"serverName"`
ServerIp string `xml:"serverIP"`
}
type Recurlyservers struct {
XMLName xml.Name `xml:"servers"`
Version string `xml:"version,attr"`
Svs []server `xml:"server"`
Description string `xml:",innerxml"`
}
接下來就是將讀取到的資料,反序列化到結構體中,
func main() {
file, err := os.Open("config/servers.xml" )
if err != nil {
fmt.Println(err)
}
defer file.Close()
body, err := ioutil.ReadAll(file)
data := new(Recurlyservers)
err = xml.Unmarshal(body, &data)
fmt.Println(data.XMLName)
fmt.Println(data.Description)
fmt.Println(data.Version)
fmt.Println(data.Svs)
}
執行結果
{ servers}
<server>
<serverName>Shanghai_VPN</serverName>
<serverIP>127.0.0.1</serverIP>
</server>
<server>
<serverName>Beijing_VPN</serverName>
<serverIP>127.0.0.2</serverIP>
</server>
1
[{{ server} Shanghai_VPN 127.0.0.1} {{ server} Beijing_VPN 127.0.0.2}]