在golang中解组到实例化的空接口

时间:2017-06-23 13:24:57

标签: xml go unmarshalling

我正在尝试解组为空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":""}
}

完整代码:https://play.golang.org/p/AsV1LGW1lR

1 个答案:

答案 0 :(得分:1)

您需要将xml标记添加到interface{},即

Content interface{} `xml:"http://e-conomic.com Debtor_GetNameResponse"`
您的其他示例中的

Address interface{}有效,因为它的名称与xml标记<Address></Address>Unmarshal的查找相同。