1

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).

1 Answer 1

1

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

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

Comments

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.