开发者

Reading the inner text of an XML element using 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 := str开发者_如何转开发ing(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?


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜