XmlNodeReader.MoveToContent Method

Summary

Advances the XmlReader to the next content node (or the current node if it is already a content node) and returns the XmlNodeType of that node.

Syntax

public override XmlNodeType MoveToContent();

Return Value

Returns the XmlNodeType of the node the reader is positioned on after the method returns. If there are no more content nodes, it returns XmlNodeType.None.

Exceptions

ExceptionCondition
XmlExceptionInvalid XML is encountered while moving to content.
ObjectDisposedExceptionThe XmlNodeReader has been closed.

Remarks

The method skips over nodes such as XmlNodeType.ProcessingInstruction, XmlNodeType.Comment, XmlNodeType.Whitespace, and XmlNodeType.SignificantWhitespace. It stops at elements, text, CDATA, end elements, end entities, and XML declarations.

Typical use case:

while(reader.MoveToContent() != XmlNodeType.None)
{
    // Process node
    reader.Read();
}

Example

The following example demonstrates how to use MoveToContent to read only the significant content of an XML document.

using System;
using System.Xml;

class Program
{
    static void Main()
    {
        string xml = @"
<bookstore>
    <!-- This is a comment -->
    <book genre='autobiography'>
        <title>The Autobiography of Benjamin Franklin</title>
        <author>Benjamin Franklin</author>
    </book>
    <?processing instruction?>
</bookstore>";

        using (XmlDocument doc = new XmlDocument())
        {
            doc.LoadXml(xml);
            using (XmlNodeReader reader = new XmlNodeReader(doc))
            {
                while (reader.MoveToContent() != XmlNodeType.None)
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        Console.WriteLine($""Element: {reader.Name}"");
                    }
                    else if (reader.NodeType == XmlNodeType.Text)
                    {
                        Console.WriteLine($""Text: {reader.Value}"");
                    }
                    reader.Read();
                }
            }
        }
    }
}

See Also