1. servers.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <servers version="1"> 3 <server> 4 <serverName>Shanghai_VPN</serverName> 5 <serverIP>127.0.0.1</serverIP> 6 </server> 7 <server> 8 <serverName>Beijing_VPN</serverName> 9 <serverIP>127.0.0.2</serverIP> 10 </server> 11 </servers>
2. main.go
1 package main 2 3 import ( 4 "encoding/xml" 5 "fmt" 6 "io/ioutil" 7 "os" 8 ) 9 10 type Recurlyservers struct { 11 XMLName xml.Name `xml:"servers"` 12 Version string `xml:"version,attr"` 13 Svs []server `xml:"server"` 14 } 15 16 type server struct { 17 ServerName string `xml:"serverName"` 18 ServerIP string `xml:"serverIP"` 19 } 20 21 func main() { 22 generateXML() 23 } 24 25 func generateXML() { 26 v := &Recurlyservers{Version: "1"} 27 v.Svs = append(v.Svs, server{"Shanghai_VPN", "127.0.0.1"}) 28 v.Svs = append(v.Svs, server{"Beijing_VPN", "127.0.0.1"}) 29 output, err := xml.MarshalIndent(v, " ", " ") 30 if err != nil { 31 fmt.Println("error:%v\n", err) 32 } 33 os.Stdout.Write([]byte(xml.Header)) 34 os.Stdout.Write(output) 35 } 36 37 func unmarshalXML() { 38 file, err := os.Open("servers.xml") 39 if err != nil { 40 fmt.Println("error:%v", err) 41 return 42 } 43 defer file.Close() 44 data, err := ioutil.ReadAll(file) 45 if err != nil { 46 fmt.Println("error:%v, err") 47 return 48 } 49 v := Recurlyservers{} 50 err = xml.Unmarshal(data, &v) 51 if err != nil { 52 fmt.Println("error:%v", err) 53 return 54 } 55 fmt.Println(v) 56 }
有疑问加站长微信联系(非本文作者)