Home > front end >  Why simple XML parser doesn't fill struct
Why simple XML parser doesn't fill struct

Time:10-29

Trying to implement a simple XML parsing, the code below doesn't work as expected.
It just returns a {[]} empty Results, while it should fill it.

Why ?...

package main
import "fmt"
import "encoding/xml"
import "bytes"

type Name struct {
    Name    string  `xml:"NAME"`
}
type Results struct {
    Names   []Name `xml:"RESULTS"`
}

func main() {
    data := []byte(`
<?xml version="1.0" encoding="UTF-8"?>
<RESULTS>
 <NAME>Apple</NAME>
 <NAME>Banana</NAME>
</RESULTS>
`)
    var r Results
    decoder := xml.NewDecoder(bytes.NewBuffer(data))
    unError := decoder.Decode(&r)
    if unError != nil {
        fmt.Println("XML Unmarshaling error:", unError )
    }else{
        fmt.Printf("%v", r)
    }
}

Tryed in the Playground, and locally (go1.17.2).

CodePudding user response:

I would suggest you to use a online struct generator like xmltogo, so use this as:

type RESULTS struct {
    XMLName xml.Name `xml:"RESULTS"`
    Text    string   `xml:",chardata"`
    NAME    []string `xml:"NAME"`
} 

Try on playground

  • Related