英文:
How does a simple xml element unmarshal to a golang struct?
问题
假设有以下的 XML 元素,其中包含一个属性和一个浮点数值:
<thing prop="1">
1.23
</thing>
<thing prop="2">
4.56
</thing>
为了解析它,我应该如何定义我的结构体?
type ThingElem struct {
Prop int `xml:"prop,attr"`
Value float64 // ???
}
type ThingWrapper struct {
T ThingElem `xml:"thing"`
}
// 或者
type ThingElem struct {
XMLName xml.Name `xml:"thing"` // 我是否需要这个属性?
Prop int `xml:"prop,attr"`
Value float64 // ???
}
XMLName 属性的使用让我感到困惑。它应该放在结构体中的哪个位置?还是应该作为标签放在一个包装器中?
英文:
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
得分: 7
以下是解析给定数据的代码。
- 在消除空格之前,无法正确解析浮点值。
- 可以使用",chardata"注释引用标签的内容。
- 只要不会产生歧义,就不需要在结构中指定
xml.Name
字段。
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)
}
希望对你有帮助!
英文:
Below you can find the code to unmarshal the given data.
- The float values cannot be correctly unmarshalled until you get rid of spaces.
- The contents of the tag can be referenced using ",chardata" annotation.
- 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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论