【问题标题】:Unmarshalling to instantiated empty interface in golang在golang中解组到实例化的空接口
【发布时间】: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":""}
}

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

【问题讨论】:

  • 你不能实例化一个接口,你只能有一个接口类型的变量来保存一个具体类型的实例。
  • @Adrian,这就是我的意思。我已经编辑了问题。
  • 请在此处提供相关代码示例。

标签: xml go unmarshalling


【解决方案1】:

您需要将xml标签添加到您的interface{},即。

Content interface{} `xml:"http://e-conomic.com Debtor_GetNameResponse"`

Address interface{} 在您的其他示例中有效,因为它的名称与它所查找的 xml 标记 &lt;Address&gt;&lt;/Address&gt;Unmarshal 相同。

【讨论】:

  • 你是对的。伙计,我真的不喜欢 go 中的 xml 处理。
猜你喜欢
  • 2020-05-15
  • 2013-05-20
  • 1970-01-01
  • 1970-01-01
  • 2018-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多