Mega Code Archive

 
Categories / C# / XML
 

XmlReader represents a reader that provides non-cached, forward-only access to XML data

using System; using System.Linq; using System.Xml; using System.IO; using System.Xml.Linq; using System.Collections; using System.Collections.Generic; public class MainClass {     public static void Main()     {         String xmlString =                 @"<?xml version='1.0'?>                     <!-- This is a sample XML document -->                     <Items>                       <Item>test with a child element <more/> stuff</Item>                     </Items>";         StringWriter output = new StringWriter();         using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))         {             XmlWriterSettings ws = new XmlWriterSettings();             ws.Indent = true;             using (XmlWriter writer = XmlWriter.Create(output, ws))             {                 while (reader.Read())                 {                     switch (reader.NodeType)                     {                         case XmlNodeType.Element:                             writer.WriteStartElement(reader.Name);                             break;                         case XmlNodeType.Text:                             writer.WriteString(reader.Value);                             break;                         case XmlNodeType.XmlDeclaration:                         case XmlNodeType.ProcessingInstruction:                             writer.WriteProcessingInstruction(reader.Name, reader.Value);                             break;                         case XmlNodeType.Comment:                             writer.WriteComment(reader.Value);                             break;                         case XmlNodeType.EndElement:                             writer.WriteFullEndElement();                             break;                     }                 }             }         }         Console.WriteLine(output.ToString());     } }