使用Go语言读取XML元素的内部文本

huangapple go评论88阅读模式
英文:

Reading the inner text of an XML element using Go

问题

我正在尝试使用xml包(http://golang.org/pkg/xml/)在Go中读取XML文件。

我的问题是我不确定如何读取元素的内部文本。我将文档加载到xml.Parser中,然后调用parser.Token()来遍历文件。我使用以下代码检查令牌是什么:

token, err := parser.Token()
if element, ok := token.(xml.StartElement); ok {
  // 作为开始元素处理。我可以在这里读取元素名称和属性
}

if charData, ok := token.(xml.CharData); ok {
  // 作为文本处理。我如何读取文本数据?
}

xml.CharData类型被定义为:

type CharData []byte

但是我似乎无法将charData变量用作字节数组以转换为字符串。CharData仅定义了一个复制令牌的方法,但这只会得到另一个CharData变量的副本。我尝试了一些方法,但它们无法编译通过:

innerText := string(charData)
innerText := string(charData[0:])
innerText := string(charData[0]) // 这个编译通过了,但不是我想要的

是否有其他方法将xml.CharData变量视为字节切片?

英文:

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?

答案1

得分: 4

根据语言规范,您应该能够执行<code>string([]byte(charData))</code>。

<code>[]byte</code> -> <code>string</code> 是一种特殊情况的类型转换。通常,新类型和原始类型必须具有相同的基础类型(即xml.CharData和[]byte)。

英文:

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

<code>[]byte</code> -> <code>string</code> 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)

huangapple
  • 本文由 发表于 2010年7月28日 00:03:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/3345552.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定