XmlTextReader reader = new XmlTextReader("example.xml"); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "book") { string outerXml = reader.ReadOuterXml(); Console.WriteLine(outerXml); } }
using (XmlTextReader reader = new XmlTextReader("example.xml")) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "employee") { string outerXml = reader.ReadOuterXml(); var employee = XElement.Parse(outerXml); Console.WriteLine(employee.Element("name").Value); } } }In this code example, the XmlTextReader is also used to read an XML file, but this time the "employee" element is targeted. The ReadOuterXml method is called to get the entire "employee" element as a string, which is then converted to an XElement object using XElement.Parse. The code then extracts the "name" element from the XElement object and prints its value to the console. Both examples demonstrate how the ReadOuterXml method is used to extract the entire current element as a string, which can then be manipulated to extract relevant elements or data. The package library used is System.Xml.