开发者

How do I use xmlTextReader to extract values?

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 the开发者_运维百科n 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.


Unless performance is really important, I would suggest using LINQ to XML:

Dim elem = XElement.Parse(testXml)

Dim puppyCount = CType(elem.Element("Puppies").Value, integer)
Dim kittenCount = CType(elem.Element("Kittens").Value, integer)


I struck the same problem with both XMLTextReader and XMLReader. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜