Depth Property
Definition
public override int Depth { get; }
Gets the depth of the current node in the XML document.
Remarks
The Depth
property returns the zero‑based depth of the current node within the XML document. The root element has a depth of 0, its children have a depth of 1, and so on. The property is read‑only and reflects the state of the underlying XmlReader
instance.
- Depth is incremented when moving to a child node.
- Depth is decremented when moving back to the parent.
- When the reader is positioned on an
XmlNodeType.Attribute
, the depth reflects the depth of the element that owns the attribute.
Example
using System;
using System.Xml;
class Program
{
static void Main()
{
string xml = @"<bookstore>
<book genre='autobiography'>
<title>The Story of My Life</title>
</book>
</bookstore>";
using (XmlReader reader = XmlReader.Create(new System.IO.StringReader(xml)))
using (XmlNodeReader nodeReader = new XmlNodeReader(new XmlDocument()))
{
nodeReader.Read(); // advance to the first node
while (nodeReader.Read())
{
Console.WriteLine($"{new string(' ', nodeReader.Depth * 2)}{nodeReader.NodeType}: {nodeReader.Name}");
}
}
}
}
Output:
Element: bookstore
Element: book
Attribute: genre
Element: title
Text: The Story of My Life
EndElement: title
EndElement: book
EndElement: bookstore