XmlNodeReader.ReadSubtree Method

Reads the subtree starting at the current node and returns it as a new XmlReader.

public XmlReader ReadSubtree();

Syntax

public XmlReader ReadSubtree();

Parameters

This method has no parameters.

Returns

Type
XmlReader
Description
An XmlReader that reads the subtree starting at the current node. The reader is positioned at the current node and the subtree is read until the end of the subtree is encountered.

Remarks

Subtree Definition
The subtree includes the current node and all its descendants. When ReadSubtree is called, the returned XmlReader is positioned at the current node. Subsequent calls to Read() on the returned reader will traverse the entire subtree. The original XmlNodeReader remains at the current node. Once the returned reader has finished reading the subtree, the original reader can resume reading from the node immediately following the subtree.
Thread Safety
Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Example

C# Example

using System;
using System.Xml;

public class Example
{
    public static void Main(string[] args)
    {
        string xmlString = @"<root>
                                <parent id='1'>
                                    <child1>Value 1</child1>
                                    <child2>Value 2</child2>
                                </parent>
                                <parent id='2'>
                                    <child3>Value 3</child3>
                                </parent>
                            </root>";

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xmlString);

        XmlNode parentNode = doc.SelectSingleNode("/root/parent[@id='1']");

        if (parentNode != null)
        {
            using (XmlNodeReader nodeReader = new XmlNodeReader(parentNode))
            {
                Console.WriteLine("Reading subtree for parent node with id='1':");

                // Read the subtree
                using (XmlReader subtreeReader = nodeReader.ReadSubtree())
                {
                    while (subtreeReader.Read())
                    {
                        Console.WriteLine($"  NodeType: {subtreeReader.NodeType}, Value: {subtreeReader.Value}");
                    }
                }

                Console.WriteLine("\nResuming reading from the original reader:");
                // The original reader is still positioned at the parent node.
                // We can advance to read the next sibling node.
                if (nodeReader.ReadToFollowingSibling("parent"))
                {
                    Console.WriteLine($"\nFound next parent node with id='{nodeReader.GetAttribute("id")}'");
                }
            }
        }
    }
}