XmlNodeReader.ReadOuterXml Method

public string ReadOuterXml()
Assembly: System.Xml (in System.Xml.dll) Namespace: System.Xml Class: XmlNodeReader
Summary
Reads the outer XML tree of the current node and returns it as a string.
Return Value
A string containing the outer XML tree of the current node.
Remarks

The ReadOuterXml method reads the outer XML tree of the current node. This includes the current node itself and all of its descendants. The method returns the entire XML fragment as a string.

If the current node is an attribute, the value of the attribute is returned.

If the current node is an element, the element start tag, its contents (including child elements), and its end tag are returned.

If the current node is text, the text content is returned.

This method is useful for extracting portions of an XML document or for serializing subtrees.

Example

The following example demonstrates how to use the ReadOuterXml method to extract the outer XML of a node.


using System;
using System.Xml;

public class Example
{
    public static void Main(string[] args)
    {
        string xmlString = @"

    
        Learning XML
        Erik T. Ray
        2003
        39.95
    
    
        Everyday Italian
        Giada De Laurentiis
        2005
        30.00
    
";

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xmlString);

        XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement.FirstChild); // Positioned at the first book element

        Console.WriteLine("Outer XML of the first book:");
        Console.WriteLine(reader.ReadOuterXml());

        // Move to the title element of the first book
        if (reader.Read())
        {
            while (reader.NodeType != XmlNodeType.Element || reader.Name != "title")
            {
                if (!reader.Read()) return;
            }
            Console.WriteLine("\nOuter XML of the title element:");
            Console.WriteLine(reader.ReadOuterXml());
        }
    }
}
            

Output:

Outer XML of the first book: <book category="programming"><title lang="en">Learning XML</title><author>Erik T. Ray</author><year>2003</year><price>39.95</price></book> Outer XML of the title element: <title lang="en">Learning XML</title>