Struct defining XML Envelope with multiple prefixed namespaces

Viewed 90

how can I add multiple values to xml.Name type?

// Envelope type
type Envelope struct {
    XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ SOAP-ENV:Envelope"`    
    Header  Header
    Body    Body
}

Expected result with XML Envelope

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:login"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

Current output with the first code is as below:

 <SOAP-ENV:Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
1 Answers

Support for namespace prefixes when marshalling XML appears to be a work in progress in the standard library.

One way to obtain the desired output with xml.Marshal is to declare string fields with the ...,attr tag in your Envelope structure:

a field with tag "name,attr" becomes an attribute with the given name in the XML element.

// Envelope type
type Envelope struct {
    XMLName      xml.Name `xml:"SOAP-ENV:Envelope"`
    XmlNSSoapEnv string   `xml:"xmlns:SOAP-ENV,attr"`
    XmlNSUrn     string   `xml:"xmlns:urn,attr"`
    XmlNSXsd     string   `xml:"xmlns:xsd,attr"`
    XmlNSXsi     string   `xml:"xmlns:xsi,attr"`
    Header       Header
    Body         Body
}

And then, when initializing the Envelope struct, you assign the desired string values to those fields:

func main() {
    e := &Envelope{
        XmlNSSoapEnv: "http://schemas.xmlsoap.org/soap/envelope/",
        XmlNSUrn:     "urn:login",
        XmlNSXsd:     "http://www.w3.org/2001/XMLSchema",
        XmlNSXsi:     "http://www.w3.org/2001/XMLSchema-instance",
    }

    a, err := xml.MarshalIndent(e, "", "\t")
    if err != nil {
        panic(err)
    }
    fmt.Println(string(a))
}

This outputs:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:login" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Header></Header>
    <Body></Body>
</SOAP-ENV:Envelope>
Related