XmlNodeReader.get_Depth Method
public int get_Depth()
Gets the depth of the current node in the XML document.
Remarks
The Depth property indicates how many levels of parent nodes the current node has. The root element is at depth 0. Attributes are not counted.
This property is useful for tracking the current position within the XML hierarchy while iterating through the document.
Example
using System;
using System.Xml;
public class Example
{
public static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<root><element attr='value'>text</element></root>");
XmlNodeReader reader = new XmlNodeReader(doc);
while (reader.Read())
{
Console.WriteLine($"Node Type: {reader.NodeType}, Depth: {reader.Depth}");
if (reader.NodeType == XmlNodeType.Element)
{
Console.WriteLine($" Name: {reader.Name}");
// Reading attributes will not increase the depth.
while (reader.MoveToNextAttribute())
{
Console.WriteLine($" Attribute: {reader.Name} = {reader.Value}, Depth: {reader.Depth}");
}
// Move back to the element node.
reader.MoveToElement();
}
}
reader.Close();
}
}
Output
Node Type: Element, Depth: 0
Name: root
Node Type: Element, Depth: 1
Name: element
Attribute: attr = value, Depth: 1
Node Type: Text, Depth: 2
Node Type: EndElement, Depth: 1
Node Type: EndElement, Depth: 0