dongyan3562 2014-05-14 08:54
浏览 66
已采纳

Go中解码XML的问题

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条回答 默认 最新

  • dongshen5115 2014-05-14 08:59
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析