我正在尝试使用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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。