Golang XML: unmarshal ignores namespace

强颜欢笑 提交于 2021-02-10 18:50:37

问题


I'm implementing a service in our Go system that reads data from an external SOAP service. Now that I'm writing tests for it, I run into this issue:

unable to unmarshal request body for testing: expected element type <soapenv:Envelope> but have <Envelope>

If I dump my data, I have this:

<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope" xmlns:v2 [...]

So I do have the correct namespace in the XML. For the record, this is the struct into which I'm trying to unmarshal the data:

type collectRequestXML struct {
    XMLName xml.Name `xml:"soapenv:Envelope"`
    SoapEnv string   `xml:"xmlns:soapenv,attr"`
    XMLNs   string   `xml:"xmlns:v2,attr"`
    Header  struct{} `xml:"soapenv:Header"`
    Body    struct {
        [...]
    }
}

What can I do to make the unmarshal fail?

See this Playground item for reference.


回答1:


The documentation of the XML package does not write enough about the namespaces. The parsing is very simple. There is a small support for the namespaces. It can parse the XML, but when you create XML ist does not support the namespace thing enough.

Your struct works, when you remove the namespace information inside the XMLName definition:

type myStruct struct {
    XMLName xml.Name `xml:"Envelope"`
    SoapEnv string   `xml:"xmlns:soapenv,attr"`
    Header  struct{} `xml:"soapenv:Header"`
    Body    struct {
        MyData string `xml:"my-data"`
    }
}

https://play.golang.org/p/UppXwx0X0i9



来源:https://stackoverflow.com/questions/55337517/golang-xml-unmarshal-ignores-namespace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!