drmq16019 2014-11-13 14:55
浏览 45
已采纳

一个简单的xml元素如何解组到golang结构?

Assume the following xml element, with an attribute and a floating point value:

<thing prop="1">
  1.23
</thing>
<thing prop="2">
  4.56
</thing>

In order to unmarshal it, how should I define my struct?

type ThingElem struct {
    Prop  int   `xml:"prop,attr"`
    Value float // ???
}

type ThingWrapper struct {
    T ThingElem `xml:"thing"`
}

// VS

type ThingElem struct {
    XMLName xml.Name `xml:"thing"` // Do I even need this?
    Prop    int      `xml:"prop,attr"`
    Value   float    // ???
}

The usage of the XMLName Property confuses me. When should it be placed in the struct, and when in a wrapper as tag?

  • 写回答

1条回答 默认 最新

  • dpbz14739 2014-11-13 16:10
    关注

    Below you can find the code to unmarshal the given data.

    1. The float values cannot be correctly unmarshalled until you get rid of spaces.
    2. The contents of the tag can be referenced using ",chardata" annotation.
    3. You do not need to specify xml.Name field in structure as long as it is not ambiguous which structure should be used.

    package main
    
    import (
        "encoding/xml"
        "fmt"
    )
    
    type Root struct {
        Things []Thing `xml:"thing"`
    }
    
    type Thing struct {
        Prop  int     `xml:"prop,attr"`
        Value float64 `xml:",chardata"`
    }
    
    func main() {
        data := `
    <root>
    <thing prop="1">1.23</thing>
    <thing prop="2">4.56</thing>
    </root>
    `
        thing := &Root{}
        err := xml.Unmarshal([]byte(data), thing)
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(thing)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来