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 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)