我正在尝试使用 xml 包 ( http://golang.org/pkg/xml/ ) 在 Go 中读取 XML 文件。
我的问题是我不确定如何阅读元素的内部文本。我将文档加载到 xml.Parser 中,然后调用 parser.Token() 在文件中移动。我检查 token 使用以下内容:
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?
}
xml.CharData 类型定义为:
type CharData []byte
但我似乎无法使用 charData 变量作为字节数组来转换为字符串。为 CharData 定义的唯一方法是复制 token ,但这只会提供 CharData 变量的另一个副本。我已经尝试了一些东西,但它们没有编译:
innerText := string(charData)
innerText := string(charData[0:])
innerText := string(charData[0]) // this compiled but is not what I want
是否有另一种方法将 xml.CharData 变量视为 byte slice ?
最佳答案
根据语言规范,您应该能够执行 string([]byte(charData))
。
[]byte
-> string
是类型转换的特例。通常,新类型和原始类型必须具有相同的底层类型(即 xml.CharData 和 []byte)
关于xml - 使用 Go 读取 XML 元素的内部文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3345552/