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.
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());
}
}
}