golang unmarshal

my.xml中的内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<servers version="199">
<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>
实现代码如下:
package main

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

// 抽取单个server对象
type Server struct {
ServerName string `xml:"serverName"`
ServerIP string `xml:"serverIP"`
}

/* https://golang.org/pkg/encoding/xml/#Unmarshal
* If the XMLName field has an associated tag of the form
"name" or "namespace-URL name", the XML element must have
the given name (and, optionally, name space) or else Unmarshal
returns an error.*/
type Servers struct {
XMLName xml.Name `xml:"servers"` // 只有变量名字叫XMLName才能解析出来
Version int `xml:"version,attr"`
Servers []Server `xml:"server"`
}

func main() {
data, err := ioutil.ReadFile("./data_format/my.xml")
if err != nil {
fmt.Println(err)
return
}
var servers = Servers{}
err = xml.Unmarshal([]byte(data), &servers)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(servers.XMLName)
fmt.Println(servers)
}
注意点:
结构体中标签的名字必须取名为XMLName,否则解析不出来。这是golang文档中的解释

 

posted @ 2020-08-06 10:59  逗你玩12  阅读(784)  评论(0编辑  收藏  举报