Golang XML 解组数组不起作用

发布于 2025-01-10 05:11:08 字数 1267 浏览 1 评论 0原文

下面是我尝试解组的代码的一个简单示例:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文