Read xml with XmlReader in CSharp

Description

The following code shows how to read xml with XmlReader.

Example


  //w w w.  j av a 2s  .com
  
  
     
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());
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    XML »




Load Parse
Document
Element
Attribute
Namespace
Query
Save
Schema
Style