xml - 使用 Go 读取 XML 元素的内部文本

标签 xml go

我正在尝试使用 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/

相关文章:

go - 如何使用 google/jsonapi 和 echo 框架返回有效的 jsonapi 响应

go - 返回数组作为接口(interface)

android - android中的dom xml解析

java - 如何从 XML 绑定(bind)中排除属性

mysql - 如何使用exec.Command登录mysql

concurrency - 游览练习 #7 : Walking the tree

go - 在Visual Studio代码中调试cgo会产生“多个定义”错误

java - 使用 JDOM 解析时处理特殊字符

查询。递归解析 XML 子项。如何?

python - lxml objectify 看不到根