英文:
Problems decoding XML in go
问题
我有一个关于在Go中解析XML的问题。
我一直在尝试解析这段XML:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<folders>
<folder id="78" name="Test 1" />
<folder id="95" name="Test 2" />
<folder id="96" name="Test 3" />
</folders>
</response>
这是我的结构体:
type XmlResponse struct {
Folders []Folder `xml:"folders>folder"`
}
type Folder struct {
XMLName xml.Name `xml:"folder"`
Id int `xml:"id,attr"`
Name string `xml:"name,attr"`
}
由于某种原因,Go不会将每个文件夹解析为文件夹数组,如结构体中定义的那样。相反,我得到了以下消息:
"expected element type <folder> but have <folders>"
正如你所看到的,我已经将xml:"folders"
添加到文件夹列表中,但它仍然无法正确识别。我尝试将XMLName属性放在不同的位置,但要么出现上述错误,要么只得到一个空的XmlResponse结构体。我还尝试创建一个包含文件夹数组的Folders结构体,结果相同。我是否在XML解码方面有什么概念上的错误?名称可能太接近了吗?
我在Go Playground上制作了一个示例,展示了这个问题:http://play.golang.org/p/XRCGVNzO_O
非常感谢。
英文:
I have a question regarding unmarshalling of XML in Go.
I have been trying to unmarshal this piece of XML
<?xml version="1.0" encoding="UTF-8"?>
<response>
<folders>
<folder id="78" name="Test 1" />
<folder id="95" name="Test 2" />
<folder id="96" name="Test 3" />
</folders>
</response>
These are my structs
type XmlResponse struct {
Folders []Folder `xml:"folders"`
}
type Folder struct {
XMLName xml.Name `xml:"folder"`
Id int `xml:"id,attr"`
Name string `xml:"name, attr"`
}
For some reason, Go won't unmarshal each folder into an array of folders, as defined in the struct. Instead i get the message
"expected element type <folder> but have <folders>"
As you can see, i have added xml:"folders"
to the list of folders, but it still won't recognize it correctly. I have tried to place the XMLName attributes in different places but i either end up with the above error, or just an empty XmlResponse struct. I have also tried to make a Folders struct containing an array of Folders, with the same result. Am i conceptually missing something regarding XML decoding? Are the names maybe a little too close to eachother?
I have made an example on Go playground that shows the issue: http://play.golang.org/p/XRCGVNzO_O
Thank you very much.
答案1
得分: 3
你需要将xml:"folders"
的元数据更改为xml:"folders>folder"
,以匹配folders
元素内的folder
元素。
请参考这个修改后的playground示例。
英文:
You need to change the xml:"folders"
meta to xml:"folders>folder"
to match the folder
elements inside the folders
element.
See this modified playground example.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论