douzhu3367 2017-07-06 23:09
浏览 21
已采纳

将XML解组到Go中的嵌入式结构

I have a flat XML structure, which I want to unmarshall in to a struct which has one part embedded. Is this possible? What is the syntax, or what custom method can I write?

In this example, I tag the nested struct with a guess: xml:"", which is skipped over by "encoding/xml".

type FloatHolder struct {
    Value float32    `xml:"value"`
}


type pv struct {
    XMLName    xml.Name  `xml:"series"`
    Test1 FloatHolder `xml:""`   // does not populate :-(
    Test2 FloatHolder `xml:"nested"` // populates
}
func main() {
    contents := `<series>
                   <nested>
                     <value>1234</value>
                   </nested>
                   <value>1234</value>
                 </series>`

    m := &pv{}

    err := xml.Unmarshal([]byte(contents), &m)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%f %f
", m.Test1.Value, m.Test2.Value)
}

Output: "0.000000 1234.000000"

Playground: https://play.golang.org/p/aEdDLFYqL5

Thanks!

  • 写回答

1条回答 默认 最新

  • dongying3744 2017-07-06 23:57
    关注

    EDIT: After comment interaction.

    Yes you can. Let's say

    XML:

    <series>
        <value>123456</value>
    </series>
    

    Struct definition:

    type FloatHolder struct {
        Value float32 `xml:",chardata"`
    }
    
    type pv struct {
        XMLName xml.Name    `xml:"series"`
        Test2   FloatHolder `xml:"value"`
    }
    

    Go Playground link: https://play.golang.org/p/9sWQaw0HlS


    Actually it's not a nested field, as per your XML. It belongs to series element.

    Update your struct to following:

    type pv struct {
        XMLName xml.Name    `xml:"series"`
        Test1   float32     `xml:"value"`
        Test2   FloatHolder `xml:"nested"`
    }
    

    Go Playground Link: https://play.golang.org/p/-mWrUMJXxX

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

报告相同问题?

悬赏问题

  • ¥15 Labview机器人问题
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr