有!
我正在解析xml文档并将其内容解组到结构中,但它只返回列表中的最后一项而不是完整列表。
列表为serverList
,在解组之后,它仅返回最后server
个实例。需要帮助。
func main() {
xmlFile := `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<operationGetServerList>
<returnCode>0</returnCode>
<message></message>
<serverList>
<server>
<serverId>1</serverId>
<nauServer>Main</nauServer>
<serverIp>1.1.1.1</serverIp>
<serverPort>8080</serverPort>
<serverPortFtp>25</serverPortFtp>
<serverHome>true</serverHome>
<serverIsOnline>true</serverIsOnline>
</server>
<server>
<serverId>2</serverId>
<nauServer>Reg1</nauServer>
<serverIp>1.1.1.2</serverIp>
<serverPort>8080</serverPort>
<serverPortFtp>25</serverPortFtp>
<serverHome>false</serverHome>
<serverIsOnline>false</serverIsOnline>
</server>
</serverList>
</operationGetServerList>`
type serverInfo struct {
ServerID string `xml:"serverId"`
NauServer string `xml:"nauServer"`
ServerIP string `xml:"serverIp"`
ServerPort int `xml:"serverPort"`
ServerPortFtp int `xml:"serverPortFtp"`
ServerHome bool `xml:"serverHome"`
ServerIsOnline bool `xml:"serverIsOnline"`
}
type serverInstance struct {
Server serverInfo `xml:"server"`
}
type operationGetServerListResponce struct {
ReturnCode int `xml:"returnCode"`
Message string `xml:"message"`
ServerList []serverInstance `xml:"serverList"`
}
var sL operationGetServerListResponce
err := xml.Unmarshal([]byte(xmlFile), &sL)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v", sL)
}
打印:
{ReturnCode:0 Message: ServerList:[{Server:{ServerID:4 NauServer:Res2 ServerIP:1.1.1.4 ServerPort:8080 ServerPortFtp:25 ServerHome:false ServerIsOnline:true}}]}
答案 0 :(得分:1)
XML没有ServerList
列表,而ServerList
包含Server
列表。
您需要将结构更改为以下内容:
type serverInstance struct {
Server []serverInfo `xml:"server"`
}
type operationGetServerListResponce struct {
ReturnCode int `xml:"returnCode"`
Message string `xml:"message"`
ServerList serverInstance `xml:"serverList"`
}
这将正确输出所有服务器:
{ReturnCode:0 Message: ServerList:{Server:[{ServerID:1 NauServer:Main
ServerIP:1.1.1.1 ServerPort:8080 ServerPortFtp:25 ServerHome:true
ServerIsOnline:true} {ServerID:2 NauServer:Reg1 ServerIP:1.1.1.2
ServerPort:8080 ServerPortFtp:25 ServerHome:false
ServerIsOnline:false} {ServerID:3 NauServer:Res1 ServerIP:1.1.1.3
ServerPort:8080 ServerPortFtp:25 ServerHome:false
ServerIsOnline:false} {ServerID:4 NauServer:Res2 ServerIP:1.1.1.4
ServerPort:8080 ServerPortFtp:25 ServerHome:false
ServerIsOnline:true}]}}