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 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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择