【发布时间】:2017-06-23 13:24:57
【问题描述】:
我正在尝试解组为空的 go 接口类型的变量。具体类型具有适当的 xml 标签,但由于某种原因,我无法解组 xml 值。他们只是空无一人。
这段代码做了我想做的事:
type Address struct {
City, State string
}
type Result struct {
XMLName xml.Name `xml:"Person"`
Name string `xml:"FullName" json:"FullName"`
Address interface{}
}
func main() {
xmlAddress := &Address{}
xmlResult := &Result{Name: "none", Address: xmlAddress}
xmlData := `
<Person>
<FullName>Mike McCartney</FullName>
<Address>
<City>Austin</City>
<State>Texas</State>
</Address>
</Person>
`
err := xml.Unmarshal([]byte(xmlData), xmlResult)
// xmlResult = {"XMLName":{"Space":"","Local":"Person"},"FullName":"Mike McCartney","Address":{"City":"Austin","State":"Texas"}}
}
完整代码:https://play.golang.org/p/QXyoOPMFZr
但在我自己的示例中,带有命名空间的实际 xml 它不起作用:
type Envelope struct {
XMLName xml.Name `xml:"http://www.w3.org/2003/05/soap-envelope Envelope"`
Body Body `xml:"http://www.w3.org/2003/05/soap-envelope Body"`
}
type Body struct {
XMLName xml.Name `xml:"http://www.w3.org/2003/05/soap-envelope Body"`
Content interface{}
}
type DebtorGetNameResponse struct {
XMLName xml.Name `xml:"http://e-conomic.com Debtor_GetNameResponse"`
DebtorGetNameResult string `xml:"Debtor_GetNameResult"`
}
func main() {
xmlData := `
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:Body>
<Debtor_GetNameResponse xmlns="http://e-conomic.com">
<Debtor_GetNameResult>THIS SHOULD BE IN THE OUTPUT</Debtor_GetNameResult>
</Debtor_GetNameResponse>
</soap:Body>
</soap:Envelope>`
e := new(Envelope)
res := new(DebtorGetNameResponse)
e.Body = Body{Content: res}
err := xml.Unmarshal([]byte(xmlData), e)
// res = {"XMLName":{"Space":"","Local":""},"DebtorGetNameResult":""}
}
【问题讨论】:
-
你不能实例化一个接口,你只能有一个接口类型的变量来保存一个具体类型的实例。
-
@Adrian,这就是我的意思。我已经编辑了问题。
-
请在此处提供相关代码示例。
标签: xml go unmarshalling