Golang XML: unmarshal ignores namespace

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.

Upvotes: 3

Views: 1806

Answers (1)

apxp
apxp

Reputation: 5914

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

Upvotes: 1

Related Questions