小编Ada*_*han的帖子

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

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

我的问题是我不确定如何读取元素的内部文本.我在xml.Parser中加载文档,然后调用parser.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?
}
Run Code Online (Sandbox Code Playgroud)

xml.CharData类型定义为:

type CharData []byte
Run Code Online (Sandbox Code Playgroud)

但我似乎无法将charData变量用作转换为字符串的字节数组.为CharData定义的唯一方法是复制令牌,但这只是给出CharData变量的另一个副本.我尝试过一些东西,但是他们没有编译:

innerText := string(charData)
innerText := string(charData[0:])
innerText := string(charData[0]) // this compiled but is not what I want
Run Code Online (Sandbox Code Playgroud)

是否有另一种方法将xml.CharData变量视为一个字节片?

xml go

8
推荐指数
1
解决办法
2086
查看次数

标签 统计

go ×1

xml ×1