简体   繁体   English

在go中解码XML的问题

[英]Problems decoding XML in go

I have a question regarding unmarshalling of XML in Go. 我有一个关于在Go中解组XML的问题。

I have been trying to unmarshal this piece of 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>

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. 出于某种原因,Go不会将每个文件夹解组为文件夹数组,如结构中所定义。 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. 如您所见,我已将xml:"folders"添加到文件夹列表中,但仍无法正确识别它。 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. 我试图将XMLName属性放在不同的位置,但我最终得到上面的错误,或者只是一个空的XmlResponse结构。 I have also tried to make a Folders struct containing an array of Folders, with the same result. 我还尝试创建一个包含文件夹数组的Folders结构,结果相同。 Am i conceptually missing something regarding XML decoding? 我在概念上缺少关于XML解码的东西吗? 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 我在Go操场上做了一个例子来说明问题: http//play.golang.org/p/XRCGVNzO_O

Thank you very much. 非常感谢你。

You need to change the xml:"folders" meta to xml:"folders>folder" to match the folder elements inside the folders element. 您需要更改的xml:"folders"元到xml:"folders>folder"相匹配的folder里面的元素folders元素。

See this modified playground example . 查看此修改过的游乐场示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM