Golang XML 解组数组不起作用
下面是我尝试解组的代码的一个简单示例:
package main
import (
"encoding/xml"
"fmt"
)
type Entry struct {
XMLName xml.Name `xml:"entry"`
Name string `xml:"name,attr"`
}
type Directory struct {
XMLName xml.Name `xml:"directory"`
Count string `xml:"count,attr"`
Entries []Entry
}
func main() {
var (
dir Directory
xmldata = `
<directory count="2">
<entry name="file-1"/>
<entry name="new-file-2"/>
</directory>
`
)
err := xml.Unmarshal([]byte(xmldata), &dir)
if err != nil {
fmt.Println(err)
}
fmt.Printf("Count : %v\n", dir.Count)
// none entry found ???
fmt.Printf("Length of entries: %d", len(dir.Entries))
for _, e := range dir.Entries {
fmt.Println("Entry: " + e.Name)
}
}
问题是条目数组是空的,无论有多少“条目”XML 标记,都没有被解组。 当我填充 Directory 对象并将其编组到字符串中时,我得到了这样的结果:
<directory count="4"><entry name="file-1"></entry><entry name="new-file-2"></entry></directory>
但是当我再次将其解组时,我只得到了 Directory 对象的 count 属性,其中填充了 4,并且数组中没有任何条目。
有谁知道我在哪里犯了一个错误,即编组工作正常但无法解组它?
below is a simple example of the code I'm trying to unmarshal:
package main
import (
"encoding/xml"
"fmt"
)
type Entry struct {
XMLName xml.Name `xml:"entry"`
Name string `xml:"name,attr"`
}
type Directory struct {
XMLName xml.Name `xml:"directory"`
Count string `xml:"count,attr"`
Entries []Entry
}
func main() {
var (
dir Directory
xmldata = `
<directory count="2">
<entry name="file-1"/>
<entry name="new-file-2"/>
</directory>
`
)
err := xml.Unmarshal([]byte(xmldata), &dir)
if err != nil {
fmt.Println(err)
}
fmt.Printf("Count : %v\n", dir.Count)
// none entry found ???
fmt.Printf("Length of entries: %d", len(dir.Entries))
for _, e := range dir.Entries {
fmt.Println("Entry: " + e.Name)
}
}
The problem is that the array of entries is empty, no matter how many "entry" XML tags there are none that is unmarshalled.
When I filled the Directory object and Marshalled it into a string I've got something like this:
<directory count="4"><entry name="file-1"></entry><entry name="new-file-2"></entry></directory>
but when I put this again to unmarshal I've got only the count attribute of Directory object filled with 4 and none entries in the array.
Does anyone know where I have made a mistake that marshalling works fine but it is impossible to unmarshal it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论