参考这篇文章https://segmentfault.com/a/1190000016932102
例子
package main
import (
"encoding/xml"
"fmt"
"os"
)
type Server struct {
XMLName xml.Name `xml:"server"`
ServerName string `xml:"serverName"`
ServerIP string `xml:"serverIP"`
}
type XMLServers struct {
XMLName xml.Name `xml:"servers"`
Version string `xml:"version,attr"`
Servers []Server `xml:"server"`
Description string `xml:",innerxml"`
}
func main() {
v := &XMLServers{
Version: "1",
}
v.Servers = append(v.Servers, Server{
ServerName: "Shanghai_VPN",
ServerIP: "127.0.0.1",
})
v.Servers = append(v.Servers, Server{
ServerName: "Beijing_VPN",
ServerIP: "127.0.0.2",
})
output, err := xml.MarshalIndent(v, "", " ")
if err != nil {
fmt.Println(err)
return
}
os.Stdout.Write([]byte(xml.Header))
os.Stdout.Write(output)
}
生成的内容如下
<?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>