XmlDocument.ReadNode Method (XmlReader)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Creates an XmlNode object based on the information in the XmlReader. The reader must be positioned on a node or attribute.

Namespace:   System.Xml
Assembly:  System.Xml (in System.Xml.dll)

[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
public virtual XmlNode ReadNode(
	XmlReader reader


Type: System.Xml.XmlReader

The XML source

Return Value

Type: System.Xml.XmlNode

The new XmlNode or null if no more nodes exist.

Exception Condition

The reader is positioned on a node type that does not translate to a valid DOM node (for example, EndElement or EndEntity).

Reads one XmlNode from the given reader and positions the reader on the next node. This method creates the type of XmlNode matching the NodeType on which the reader is currently positioned. (If the reader is in the initial state, ReadNode advances the reader to the first node and then operates on that node.)

If the reader is positioned on the start of an element, ReadNode reads all the attributes and any child nodes, up to and including the end tag of the current node. The XmlNode returned contains the sub-tree representing everything read. The reader is positioned immediately after the end tag.

ReadNode can also read attributes, but in this case it does not advance the reader to the next attribute. This allows you to write the following C# code:

XmlDocument doc = new XmlDocument();
while (reader.MoveToNextAttribute())
  XmlNode a = doc.ReadNode(reader);
  // Do some more processing.

ReadNode does consume the attribute value though, which means after calling ReadNode on an attribute, XmlReader.ReadAttributeValue returns false.

Notes to Inheritors:

This method has an inheritance demand. Full trust is required to override the ReadNode method.

This method is a Microsoft extension to the Document Object Model (DOM).

The following example uses ReadNode to create a new node and then inserts the new node into the document.

using System;
using System.IO;
using System.Xml;

public class Sample
  public static void Main()
    //Create the XmlDocument.
    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<bookstore>" +
                "<book genre='novel' ISBN='1-861001-57-5'>" +
                "<title>Pride And Prejudice</title>" +
                "</book>" +

    //Create a reader.
    XmlTextReader reader = new XmlTextReader("cd.xml");
    reader.MoveToContent(); //Move to the cd element node.

    //Create a node representing the cd element node.
    XmlNode cd = doc.ReadNode(reader);

    //Insert the new node into the document.

    Console.WriteLine("Display the modified XML...");


The example uses the file, cd.xml, as input.

<!-- sample CD -->
<cd genre='alternative'>

Universal Windows Platform
Available since 10
.NET Framework
Available since 1.1
Return to top