Gpack
Gpack

Reputation: 2203

Variable xml tag in golang

I'm trying to communicate with a SOAP service from my go program but I'm having difficulties to use the xml package.

Most of the requests I have to send have the following format:

<s:Envelope xmlns="namespace1">
 <s:Body>
      <FunctionName xmlns=“namespace2”/>
 </s:Body>
</s:Envelope>

I feel I have to create one type for each request I want to make, as FunctionNamechanges... Here's the code I use so far.

It would be nice if I could have a single type with the FunctionName as an attribute but I just can't figure out how... To make it clearer, I would like to put a variable instead of FunctionName inside xml:"s:Body>FunctionName".

Thanks a lot for your help!

Upvotes: 1

Views: 1130

Answers (1)

icza
icza

Reputation: 418745

You can use an xml.Name field to specify the tag name you want it in the XML output. Note that with xml.Name you can also specify the namespace, so you don't even need Command.Field anymore which you only used to set the namespace attribute.

So here is your modified code:

type Command struct {
    XMLName xml.Name
}

type XMLEnvelop struct {
    XMLName      xml.Name `xml:"s:Envelope"`
    Xmlns        string   `xml:"xmlns:s,attr"`
    FunctionName Command  `xml:"s:Body>FunctionName"`
}

v := &XMLEnvelop{Xmlns: "namespace1",
    FunctionName: Command{xml.Name{"namespace2", "MyFuncName"}}}

output, err := xml.MarshalIndent(v, "", "    ")
if err != nil {
    fmt.Printf("error: %v\n", err)
}

// Write the output to check
os.Stdout.Write(output)

Output (try it on the Go Playground):

<s:Envelope xmlns:s="namespace1">
    <s:Body>
        <MyFuncName xmlns="namespace2"></MyFuncName>
    </s:Body>
</s:Envelope>

Upvotes: 2

Related Questions