douchu5131 2017-06-26 19:37
浏览 108
已采纳

如何在Go中向元素添加XML属性?

I am using the encoding/xml package in Go and the Encoder example code.

While I am able to produce workable XML, I am unable to add all of the attributes that I need.

As an example, let us use the concept of temperature reporting. What I need is something like this:

<environment>
  <temperature type="float" units="c">-11.3</temperature>
</environment>

My struct looks like this:

type climate struct {
    XMLName     xml.Name    `xml:"environment"`
    Temperature string      `xml:"temperature"`
    Type        string      `xml:"type,attr"`
    Units       string      `xml:"unit,attr"`
}

What I end up with looks like this:

<environment type="float" unit="c">
  <temperature>-11.3</temperature>
</environment>

My example code in the Go Playground

How can I format the struct tags to put the attributes in the proper element?

  • 写回答

1条回答 默认 最新

  • dpt62283 2017-06-26 19:56
    关注

    Your desired XML has 2 elements: <environment> and <temperature>, so you should have 2 types (structs) to model them. And you may use the tag ",chardata" to tell the encoder to write the field's value as character data and not as an XML element.

    type environment struct {
        Temperature temperature `xml:"temperature"`
    }
    
    type temperature struct {
        Temperature string `xml:",chardata"`
        Type        string `xml:"type,attr"`
        Units       string `xml:"unit,attr"`
    }
    

    Testing it:

    x := &environment{
        Temperature: temperature{Temperature: "-11.3", Type: "float", Units: "c"},
    }
    
    enc := xml.NewEncoder(os.Stdout)
    enc.Indent("", "  ")
    if err := enc.Encode(x); err != nil {
        fmt.Printf("error: %v
    ", err)
    }
    

    It produces the desired output (try it on the Go Playground):

    <environment>
      <temperature type="float" unit="c">-11.3</temperature>
    </environment>
    

    Note that you get the same result if you use the ",innerxml" tag which tells the encoder to write the value verbatim, not subject to the usual marshaling procedure:

    type temperature struct {
        Temperature string `xml:",innerxml"`
        Type        string `xml:"type,attr"`
        Units       string `xml:"unit,attr"`
    }
    

    Output is the same. Try this one on the Go Playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料