如何使用 xmlTextReader 提取值?
我正在尝试解析此 XML 以获取小狗和小猫的值。
<Pets>
<Puppies>4</Puppies>
<Kittens>2</Kittens>
</Pets>
这是我的代码
baseReader = New IO.StringReader(testXml)
xmlReader = New System.Xml.XmlTextReader(baseReader)
While xmlReader.Read()
Select Case xmlReader.Name
Case "Puppies"
puppyCount = CLng(xmlReader.ReadInnerXml)
Case "Kittens"
kittenCount = CLng(xmlReader.ReadInnerXml)
Case Else
End Select
End While
,第一次读取时,元素名称是“Pets”,而 Case Else 被命中。在下一次读取时,元素名称为“Puppies”,puppyCount 正确设置为 4。
但随后它似乎跳过“Kittens”并直接转到内部 XML。我应该做什么?
编辑:XmlReader 比其他 .NET 解析器更快,但我的文件足够小,这可能不是一个好处。 Joe Ferner 的测试。
编辑 2:原始代码中存在读者定位问题。
I'm trying to parse this XML for the values of puppies and kittens.
<Pets>
<Puppies>4</Puppies>
<Kittens>2</Kittens>
</Pets>
Here's my code
baseReader = New IO.StringReader(testXml)
xmlReader = New System.Xml.XmlTextReader(baseReader)
While xmlReader.Read()
Select Case xmlReader.Name
Case "Puppies"
puppyCount = CLng(xmlReader.ReadInnerXml)
Case "Kittens"
kittenCount = CLng(xmlReader.ReadInnerXml)
Case Else
End Select
End While
On the first read, the element name is "Pets" and the Case Else gets hit. On the next read, the element name is "Puppies" and puppyCount is correctly set to 4.
But then it seems to skip over "Kittens" and go directly to the inner XML. What should I be doing?
EDIT: XmlReader is faster than other .NET parsers, but my files are small enough that it's probably not a benefit. Joe Ferner's tests.
EDIT 2: There's a reader positioning problem in the original code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除非性能真的很重要,否则我建议使用 LINQ to XML:
Unless performance is really important, I would suggest using LINQ to XML:
我在使用
XMLTextReade
r 和XMLReader
时遇到了同样的问题。最初的问题是.ReadInnerXML()
有时可以执行行尾读取,然后在循环顶部进行另一次读取,这当然意味着您跳过了下一个元素。您可以尝试使用.ReadString
代替 - 这对我有用。I struck the same problem with both
XMLTextReade
r andXMLReader
. The original problem is that.ReadInnerXML()
can sometimes perform an end-of-line read, and then then at the top of the loop you do another read which of course means you've skipped the next element. You can try using.ReadString
instead - this worked for me.