Can not parse xml

(cinematik) #1

I’m trying to parse xml


but I get

arr.Data undefined (type Data has no field or method Data)

I expect to output

01 Hello

02 GoodBue

(Lutz Horn) #2

A XML document has a single root element which is Data. There is nothing to iterate over. Just access the members of arr directly.

package main

import "fmt"
import "encoding/xml"

type Data struct {
	XMLName xml.Name `xml:"Data"`
	Cue     Cue      `xml:"Cue"`

type Cue struct {
	XMLName xml.Name `xml:"Cue"`
	Value   string   `xml:"value,attr"`
	Cdata   string   `xml:",chardata"`

func main() {
	x := `<?xml version='1.0'?><Data contentPath='local'><Cue value='01'><![CDATA[Hello]]></Cue><Cue value='02'><![CDATA[Goodbye]]></Cue></Data>`

	var arr Data
	xml.Unmarshal([]byte(x), &arr)


(cinematik) #3

In your version first element 01 Hello is absent. And It realy need to be iterated over for loop because it’s just a sample but real data is much bigger.

(Lutz Horn) #4

Your Data contains only a single Cue while the XML has two. The XML seems to only keep the last of those.

So if you will have to change Data so that it contains an array of Cues.

(Cecil New) #5

Some examples to learn from:

(Johan Dahl) #6

As @lutzhorn said. Like this: