0

I have this very simple peace of code and a simple XML file . I am reading each node and writing it to another file , And really strage that xml reader skips every alternate record node . It writes 1 and 3 rd node from following file ! Any help appreciated .

Do While (reader.Read())
    If (reader.NodeType = XmlNodeType.Element And (reader.LocalName = "record" Or reader.LocalName = "record1")) Then
        writer.WriteNode(reader, True)
        writer.Flush()
    End If
Loop

-

<?xml version="1.0" encoding="UTF-8"?>
<records xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="world-check.xsd">
    <record>
        <foo>
            <bar>wtf3</bar>
            <bar>wtf4</bar>
        </foo>
    </record>
    <record>
        <foo>
            <bar>wtf4</bar>
            <bar>wtf5</bar>
        </foo>
    </record>
</records>
Pit Digger
  • 9,618
  • 23
  • 78
  • 122

1 Answers1

1

Forgive my VB, I'm pretty much purely a C# developer.

XmlWriter.WriteNode() does an XmlReader.Read() past the EndElement node for the node you write, so when you get back to the start of the While loop you read past the next Record node.

Try this:

Dim reader As XmlTextReader = New XmlTextReader("1.xml")
Dim writer As XmlTextWriter = New XmlTextWriter("2.xml", Nothing)
reader.WhitespaceHandling = WhitespaceHandling.None

Dim reading as boolean = reader.Read()

Do While (reading)    
    If (reader.NodeType = XmlNodeType.Element And (reader.LocalName = "record" Or reader.LocalName = "record1")) Then
        writer.WriteNode(reader, True)
        writer.Flush()
    Else
        reading = reader.Read()
    End If
Loop
TheEvilPenguin
  • 5,634
  • 1
  • 26
  • 47
  • In VS2019 and .net 4.7.2 reader.WhitespaceHandling simply ... does not exist. That property is not there. – Prof. Falken Sep 30 '21 at 11:29
  • @Prof.Falken Are you sure you're looking at System.Xml.XmlTextReader? Seems like it [should exist](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmltextreader.whitespacehandling?view=netframework-4.7.2) – TheEvilPenguin Oct 02 '21 at 02:37
  • 1
    I double checked, and it *is* System.Xml.XmlTextReader and it doesn't exist. I solved my immediate problem another (slightly hacky) way, so leaving this mystery behind for now. – Prof. Falken Oct 05 '21 at 10:07