2014-05-14 08:54



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"?>
                <folder id="78" name="Test 1" />
                <folder id="95" name="Test 2" />
                <folder id="96" name="Test 3" />

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:

Thank you very much.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dongshen5115 dongshen5115 7年前

    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.

    点赞 评论 复制链接分享