duangu1868
duangu1868
2015-08-11 07:16
浏览 66

Golang中的可变xml标记

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!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dqm7854
    dqm7854 2015-08-11 08:55
    已采纳

    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
    ", 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>
    
    点赞 评论

相关推荐