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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?