Reading Node Trees with XmlNodeReader
The XmlNodeReader provides a reader over a given XML Document Object Model (DOM) node subtree. It reads and returns nodes from the subtree, including entity reference nodes.
The XmlNodeReader provides the following functionality:
Enforces the XML well-formedness rules.
Expands default attributes and entities, if document type definition (DTD) information is present in the XmlDocument. For more information on getting default attribute information, see the XmlNodeReader.IsDefault property.
Note
In the .NET Framework version 2.0, the recommended practice is to create XmlReader instances using the XmlReaderSettings class and the Create method. This allows you to take full advantage of all the new features introduced in the .NET Framework. For more information, see Creating XML Readers.
Example
To create an XmlNodeReader from an XmlDocument:
Dim doc As New XmlDocument()
doc.Load("MyXml.xml")
Dim nodereader As New XmlNodeReader(doc)
While nodereader.Read()
' Read the XmlDocument as a stream of XML.
End While
XmlDocument doc = new XmlDocument();
doc.Load("MyXml.xml");
XmlNodeReader nodereader = new XmlNodeReader (doc);
while (nodereader.Read()) {
// Read the XmlDocument as a stream of XML.
}
An XmlNodeReader can also be constructed with any XmlNode within the XmlDocument.
The following example moves to a particular node in the XmlDocument using the SelectSingleNode method and an XPath expression. It then creates an XmlNodeReader at that position. The XML input file, test.xml, contains the following data:
<root>
<child>
Child Text
</child>
</root>
Imports System
Imports System.Xml
Public Class Test
Public Shared Sub Main()
Dim doc As New XmlDocument()
doc.Load("test.xml")
Dim child As XmlNode = doc.SelectSingleNode("/root/child")
If Not (child Is Nothing) Then
Dim nr As New XmlNodeReader(child)
While nr.Read()
Console.WriteLine(nr.Value)
End While
End If
End Sub 'Main
End Class 'Test
using System;
using System.Xml;
public class Test {
public static void Main() {
XmlDocument doc = new XmlDocument();
doc.Load("test.xml");
XmlNode child = doc.SelectSingleNode("/root/child");
if (child != null) {
XmlNodeReader nr = new XmlNodeReader(child );
while (nr.Read() )
Console.WriteLine( nr.Value );
}
}
}
See Also
Concepts
Reading XML with the XmlReader