Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading the inner text of an XML element using Go

Tags:

xml

go

I'm trying to read an XML file in Go using the xml package (http://golang.org/pkg/xml/).

My problem is that I'm not sure how to read an element's inner text. I load the document in the xml.Parser and then call parser.Token() to move through the file. I check to see what the token is using the following:

token, err := parser.Token()
if element, ok := token.(xml.StartElement); ok {
  // process as a start element. I can read the element name and attributes here
}

if charData, ok := token.(xml.CharData); ok {
  // process as text. How do I read the text data?
}

The xml.CharData type is defined as:

type CharData []byte

but I can't seem to use the charData variable as an array of bytes to convert to a string. The only method defined for CharData is to copy the token, but that just gives another copy of a CharData variable. I've tried a few things but they don't compile:

innerText := string(charData)
innerText := string(charData[0:])
innerText := string(charData[0]) // this compiled but is not what I want

Is there another way to treat the xml.CharData variable as a slice of bytes?

like image 800
Adam Sheehan Avatar asked Jul 27 '10 16:07

Adam Sheehan


1 Answers

Based on the language spec, you should be able to do string([]byte(charData)).

[]byte -> string is a special case for type conversion. Normally, the new type and original type must have the same underlying type (i.e. xml.CharData and []byte)

like image 139
cthom06 Avatar answered Oct 03 '22 19:10

cthom06