XMLReader跳过每个备用节点

时间:2012-07-19 23:59:02

标签: xml vb.net xmlreader xmlwriter

我有这个非常简单的代码和简单的XML文件。我正在读取每个节点并将其写入另一个文件,并且确实xml阅读器会跳过每个备用记​​录节点。它从以下文件写入1和3 rd节点!任何帮助赞赏。

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>

1 个答案:

答案 0 :(得分:1)

原谅我的VB,我几乎都是纯粹的C#开发人员。

XmlWriter.WriteNode()通过您编写的节点的EndElement节点执行XmlReader.Read(),因此当您返回到While循环的开头时,您将读取通过下一个Record节点。

试试这个:

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