英文:
Can't decode XML with golang, always empty struct
问题
我正在尝试使用golang解码XML,但以下代码返回一个空的结构体。
有人可以帮忙吗?
当我运行以下代码时,总是得到:
{{ packet} []}
附上源代码:
package main
import (
"fmt"
"encoding/xml"
// "io/ioutil"
)
type Field struct {
XMLName xml.Name `xml:"field"`
name string `xml:"name,attr"`
shownameg string `xml:"showname,attr"`
fields []Field
}
type Proto struct {
XMLName xml.Name `xml:"proto"`
name string `xml:"name,attr"`
shownameg string `xml:"showname,attr"`
fields []Field
}
type Packet struct {
XMLName xml.Name `xml:"packet"`
protos []Proto `xml:"proto"`
}
func main () {
data := []byte(`
<packet>
<proto name="geninfo" pos="0" showname="General information" size="122">
<field name="timestamp" pos="0" show="Jul 17, 2008 15:50:25.136434000 CST" showname="Captured Time" value="1216281025.136434000" size="122"/>
</proto>
</packet>
`)
packet := Packet{}
err := xml.Unmarshal([]byte(data), &packet)
if err != nil {
fmt.Println (err)
return
}
fmt.Println (packet)
for proto, _ := range packet.protos {
fmt.Println (proto)
}
}
英文:
I'm trying to decode XML with golang, but the following code gives an empty struct
Anyone can help?
When I run the following code, I always get
{{ packet} []}
Attached source code:
package main
import (
"fmt"
"encoding/xml"
// "io/ioutil"
)
type Field struct {
XMLName xml.Name `xml:"field"`
name string `xml:"name,attr"`
shownameg string `xml:"showname,attr"`
fields []Field
}
type Proto struct {
XMLName xml.Name `xml:"proto"`
name string `xml:"name,attr"`
shownameg string `xml:"showname,attr"`
fields []Field
}
type Packet struct {
XMLName xml.Name `xml:"packet"`
protos []Proto `xml:"proto"`
}
func main () {
data := []byte(`
<packet>
<proto name="geninfo" pos="0" showname="General information" size="122">
<field name="timestamp" pos="0" show="Jul 17, 2008 15:50:25.136434000 CST" showname="Captured Time" value="1216281025.136434000" size="122"/>
</proto>
</packet>
`)
packet := Packet{}
err := xml.Unmarshal([]byte(data), &packet)
if err != nil {
fmt.Println (err)
return
}
fmt.Println (packet)
for proto, _ := range (packet.protos) {
fmt.Println (proto)
}
}
答案1
得分: 4
你需要按照 https://golang.org/pkg/encoding/xml/#Unmarshal 中的说明导出你的结构字段。
因为 Unmarshal 使用 reflect 包,它只能赋值给导出的(大写字母开头的)字段。Unmarshal 使用区分大小写的比较来将 XML 元素名称与标签值和结构字段名称进行匹配。
例如:
type Proto struct {
XMLName xml.Name `xml:"field"`
Name string `xml:"name,attr"`
Shownameg string `xml:"showname,attr"`
Fields []Field
}
英文:
You need to export your struct fields as per https://golang.org/pkg/encoding/xml/#Unmarshal
> Because Unmarshal uses the reflect package, it can only assign to exported (upper case) fields. Unmarshal uses a case-sensitive comparison to match XML element names to tag values and struct field names.
e.g.
type Proto struct {
XMLName xml.Name `xml:"field"`
Name string `xml:"name,attr"`
Shownameg string `xml:"showname,attr"`
Fields []Field
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论