duangu1868 2015-08-10 23: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 2015-08-11 00: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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?