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.

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

报告相同问题?

悬赏问题

  • ¥15 onlyoffice编辑完后立即下载,下载的不是最新编辑的文档
  • ¥15 求caverdock使用教程
  • ¥15 Coze智能助手搭建过程中的问题请教
  • ¥15 12864只亮屏 不显示汉字
  • ¥20 三极管1000倍放大电路
  • ¥15 vscode报错如何解决
  • ¥15 前端vue CryptoJS Aes CBC加密后端java解密
  • ¥15 python随机森林对两个excel表格读取,shap报错
  • ¥15 基于STM32心率血氧监测(OLED显示)相关代码运行成功后烧录成功OLED显示屏不显示的原因是什么
  • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。