处理XML文件
xml文件:
<?xml version="1.0" encoding="utf-8"?>
<servers version="1">
<serverName>Shanghai_VPN
<serverIP>127.0.0.1
<serverName>Beijing_VPN
<serverIP>127.0.0.2
</servers>
golang例子代码:
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
)
type Recurlyserversstruct{
XMLName xml.Name`xml:"servers"`
Versionstring `xml:"version,attr"`
Svs []server`xml:"server"`
Descriptionstring `xml:",innerxml"`
}
type serverstruct {
XMLName xml.Name`xml:"server"`
ServerNamestring `xml:"serverName"`
ServerIPstring `xml:"serverIP"`
}
func main(){
file, err := os.Open("servers.xml")
if err != nil{
fmt.Printf("error: %v",err)
return
}
defer file.Close()
data, err := ioutil.ReadAll(file)
if err != nil{
fmt.Printf("error: %v", err)
return
}
v := Recurlyservers{}
err = xml.Unmarshal(data, &v)
if err != nil{
fmt.Printf("error: %v",err)
return
}
fmt.Println(v)
}
执行结果截图:
有疑问加站长微信联系(非本文作者)