Can not parse xml

I’m trying to parse xml

playground

but I get

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

I expect to output

01 Hello

02 GoodBue

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)

	fmt.Println(arr)
	fmt.Println(arr.Cue)
}

https://play.golang.org/p/wMmflUWmNvl

1 Like

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.

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.

Some examples to learn from:

1 Like

As @lutzhorn said. Like this: https://play.golang.org/p/8EF3kIQ76QJ

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.