1

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Probably the only thing i hadn't tried. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.