I'm working on generating a SOAP message(xml) from golang. I have the following example.
package main
import (
"encoding/xml"
"fmt"
)
type Envelope struct {
XMLName xml.Name `xml:"Envelope"`
}
func main() {
envelope := Envelope{
XMLName: xml.Name{
Local: "soapenv",
Space: "http://www.w3.org/2003/05/soap-envelope",
},
}
res, _ := xml.Marshal(envelope)
fmt.Print(string(res))
}
This program prints the output as follows
<Envelope></Envelope>
I want to get the output with namespace prefix as below,
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"></soapenv:Envelope>
Can someone help me to get my desired output??
CodePudding user response:
You can add the xmlns
attribute explicitly to your struct definition:
type Envelope struct {
XMLName xml.Name `xml:"soapenv:Envelope"`
SoapEnv string `xml:"xmlns:soapenv,attr"`
}
and then to instantiate it:
e := Envelope{
SoapEnv: "http://www.w3.org/2003/05/soap-envelope",
}
https://go.dev/play/p/LrKNg8PTK2A
Output:
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"></soapenv:Envelope>
See XML docs example for more XML customizations.