加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 07:49:25 所属栏目:百科 来源:网络整理
导读:我正在尝试使用xml包( http://golang.org/pkg/xml/)在Go中读取XML文件. 我的问题是我不确定如何读取元素的内部文本.我在xml.Parser中加载文档,然后调用parser.Token()来遍历文件.我查看令牌使用以下内容: token,err := parser.Token()if element,ok := toke
我正在尝试使用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?
}

xml.CharData类型定义为:

type CharData []byte

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

innerText := string(charData)
innerText := string(charData[0:])
innerText := string(charData[0]) // this compiled but is not what I want

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

根据语言规范,你应该能够做string([] byte(charData)).

[] byte – > string是类型转换的特例.通常,新类型和原始类型必须具有相同的基础类型(即xml.CharData和[] byte)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读