douchu5131 2017-06-26 11: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 11: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.

    展开全部

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部