基于 encoding/xml
示例代码
package main
import (
"encoding/xml"
"fmt"
)
// omitempty 如果是默认值,就不参与序列化
type Member struct {
Name string `xml:"name"`
StrValue string `xml:"value>string,omitempty"`
IntValue int `xml:"value>int,omitempty"`
}
type Result struct {
XMLName xml.Name `xml:"methodResponse"`
FirstValue string `xml:"params>param>value>array>data>value>string"`
Members []Member `xml:"params>param>value>array>data>value>struct>member"`
}
func main() {
data := `
<methodResponse>
<params>
<param>
<value><array><data>
<value><string>12345abcde12345abcde12345</string></value>
<value><struct>
<member>
<name>username</name>
<value><string>trex</string></value>
</member>
<member>
<name>home</name>
<value><string>/home</string></value>
</member>
<member>
<name>mail_server</name>
<value><string>Mailbox1</string></value>
</member>
<member>
<name>web_server</name>
<value><string>Web12</string></value>
</member>
<member>
<name>id</name>
<value><int>1234</int></value>
</member>
</struct></value>
</data></array></value>
</param>
</params>
</methodResponse>`
v := Result{}
err := xml.Unmarshal([]byte(data), &v)
if err != nil {
fmt.Printf("error: %v", err)
return
}
fmt.Printf("XMLName: %#v\n", v.XMLName)
fmt.Printf("Values: %#v\n", v.FirstValue)
for _, b := range v.Members {
fmt.Printf("%s:%s:%d\n", b.Name, b.StrValue, b.IntValue)
}
fmt.Println("")
dd, err2 := xml.Marshal(v)
if err2 != nil {
fmt.Printf("err:%s\n", err2.Error())
}
fmt.Printf("%s\n", string(dd))
}
** 作为字段的标签说明: **
参考:https://blog.huangz.me/2017/go-stdlib-encoding-xml.html
原文:https://www.cnblogs.com/ghj1976/p/golang-xml-xu-lie-hua-he-fan-xu-lie-hua.html