Mega Code Archive

 
Categories / C# Book / 06 XML
 

0550 XmlReader

XmlReader is a high-performance class for reading an XML stream in a low-level, forward-only manner. Consider the following XML file: <?xml version="1.0" encoding="utf-8" standalone="yes"?> <customer id="123" status="archived"> <firstname>Jack</firstname> <lastname>Smith</lastname> </customer> using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq; using System.Text; using System.IO; class Program { static void Main() { XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreWhitespace = true; using (XmlReader reader = XmlReader.Create("customer.xml", settings)) while (reader.Read()) { Console.Write(new string(' ', reader.Depth * 2)); // Write indentation Console.WriteLine(reader.NodeType); } } } The output: XmlDeclaration Element Element Text EndElement Element Text EndElement EndElement To construct an XmlReader that reads from a string: XmlReader reader = XmlReader.Create (new System.IO.StringReader (myString));