一个简单的xml元素如何解组为一个golang结构? [英] How does a simple xml element unmarshal to a golang struct?

查看:112
本文介绍了一个简单的xml元素如何解组为一个golang结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假定下面的xml元素具有一个属性和一个浮点值:

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

为了解组,它应该如何定义我的结构?

 类型ThingElem结构{
Prop int`xml:prop,attr`
Value float // ???
}

类型ThingWrapper结构{
ThingElem`xml:thing`
}

// VS

类型ThingElem结构{
XMLName xml.Name`xml:thing`//我甚至需要这个吗?
Prop int`xml:prop,attr`
Value float // ???
}

XMLName属性的用法让我感到困惑。什么时候应该放在结构体中,以及什么时候放在包装体中作为标记? 下面你可以找到解组的代码给定的数据。


  1. 在摆脱空格之前,float值无法正确解组。

  2. 标签的内容可以使用,chardata注释来引用。

  3. 只要结构不应该使用哪个结构,就不需要在结构中指定 xml.Name 字段。






 包主

import(
encoding / xml
fmt


类型根结构{
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(东西)
}


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?

解决方案

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)
}

这篇关于一个简单的xml元素如何解组为一个golang结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆