System.Xml.XmlNodeReader.ReadToDescendant

Syntax

public bool ReadToDescendant(string name);
public bool ReadToDescendant(string name, string ns);

Parameters

Return Value

Returns true if the reader is positioned on the descendant element; otherwise, false if the end of the document is reached.

Exceptions

Remarks

ReadToDescendant reads forward in the XML document until it finds the next element with the specified local name (and optional namespace). The method does not descend into child elements of the current node; it only searches among the following sibling elements and their descendants.

Typical usage involves positioning the reader on an element and then locating a specific child element without manually iterating through all nodes.

Example

The following example demonstrates how to locate a <price> element inside a <product> node.

// XML sample
string xml = @"
<catalog>
  <product id='001'>
    <name>Laptop</name>
    <price>1200</price>
    <description>High performance laptop.</description>
  </product>
</catalog>";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
using (XmlNodeReader reader = new XmlNodeReader(doc))
{
    // Position on the first  element
    reader.ReadToFollowing("product");

    // Move to its  descendant
    if (reader.ReadToDescendant("price"))
    {
        Console.WriteLine($\"Price: {reader.Value}\");
    }
}

Related Topics