Pergunta

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.

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top