ReadToFollowing
Method
Moves the reader to the node immediately following the current node.
Syntax
public bool ReadToFollowing(string name);
Parameters
| Name | Description |
|---|---|
name |
The name of the element or attribute to move to. |
Return Value
true if the reader successfully moved to a node following the current node with the specified name; otherwise, false.
Remarks
The ReadToFollowing method reads forward through the XML document until it encounters a node with the specified name. The reader stops at the first node it finds that matches the name. If no node with the specified name is found, the reader continues to the end of the document and returns false.
This method is useful for quickly navigating to a specific element or attribute without having to manually read through intermediate nodes.
Example
The following C# code demonstrates how to use the ReadToFollowing method to find and read an element named "book":
// Assume xmlContent holds your XML data
string xmlContent = @"<catalog>
<book id=""bk101"">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications with XML.</description>
</book>
<book id=""bk102"">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description>
</book>
</catalog>";
using (StringReader reader = new StringReader(xmlContent))
{
using (XmlReader xmlReader = XmlReader.Create(reader))
{
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == "catalog")
{
// Move to the first book element after the catalog start element
if (xmlReader.ReadToFollowing("book"))
{
// Now xmlReader is positioned at the first 'book' element
Console.WriteLine($"Found book: {xmlReader.GetAttribute("id")}");
// You can now process the book element's content
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
if (xmlReader.Name == "title")
{
Console.WriteLine($" Title: {xmlReader.ReadElementContentAsString()}");
}
else if (xmlReader.Name == "author")
{
Console.WriteLine($" Author: {xmlReader.ReadElementContentAsString()}");
}
}
else if (xmlReader.NodeType == XmlNodeType.EndElement && xmlReader.Name == "book")
{
// Move to the next book or end of catalog
if (!xmlReader.ReadToFollowing("book"))
{
break; // No more books
}
// If ReadToFollowing returned true, it's already positioned at the next book
Console.WriteLine($"Found book: {xmlReader.GetAttribute("id")}");
}
}
}
}
}
}
}