Syntax
public bool ReadToDescendant(string name);
public bool ReadToDescendant(string name, string ns);
Parameters
- name – The local name of the descendant element to find.
- ns – The namespace URI of the descendant element to find (optional – overload without ns ignores namespaces).
Return Value
Returns true
if the reader is positioned on the descendant element; otherwise, false
if the end of the document is reached.
Exceptions
ArgumentNullException
–name
isnull
.InvalidOperationException
– The underlyingXmlNode
isnull
or the reader is closed.
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}\");
}
}