Thursday, March 29, 2007

* Reading & Writing XML Data

This post covers how to read and write XML data using XmlReader and XmlWriter classes provided by .NET framework.

To get the Overview of XML support in .NET Framework pls read following post.

Classes XmlReader & XmlWriter provide support for forward-only, read-only & write-only and non-cached way of reading & writing XML data.

For reading the data, XmlReader provides the support for traversing through node, data, attributes, etc. XmlReaderSettings attached to XmlReader instance controls the behaviour of XmlReader like setting the validation type, setting event handler for validation failure etc. XmlSchemaSet can be used to specify the schema file to be used in case validation is of type Schema.

For writing XML, XmlWriter provide the support for writing xml data to file in forward-only manner. XmlWriterSettings controls the behaviour of XmlWriter class like Indentation and Indentation characters to be used.

Below sample demonstrates how to read a XML file and reproduce the same file again by reading each part of xml one by one and writing it to new file. It uses the schema file to validate the xml data.

The XML used for testing is :

<Company ID="1">
<Company ID="2">
<Company ID="3">

The schema file generated using XSD.exe tool is :

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="EmployeeList" xmlns="" xmlns:xs="" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="EmployeeList" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="Company">
<xs:element name="Employee" nillable="true" minOccurs="0" maxOccurs="unbounded">
<xs:simpleContent msdata:ColumnName="Employee_Text" msdata:Ordinal="0">
<xs:extension base="xs:string">
<xs:attribute name="ID" type="xs:string" />

The code of the program :

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Schema;

namespace XMLReadWrite
class Program
static void Main(string[] args)
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(null, "EmployeeList.xsd");

XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.CheckCharacters = true;
readerSettings.ValidationType = ValidationType.Schema;
readerSettings.Schemas = schemaSet;
readerSettings.ValidationEventHandler += new ValidationEventHandler(ValCallBack);

XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.Indent = true;
writerSettings.IndentChars = "\t";

XmlReader reader = XmlReader.Create("EmployeeList.xml", readerSettings);

XmlWriter writer = XmlWriter.Create("EmployeeListNew.xml", writerSettings);

while (reader.Read())
switch (reader.NodeType)
case XmlNodeType.Element:
Console.WriteLine("element <{0}>", reader.Name);
case XmlNodeType.Text:
Console.WriteLine("text "+reader.Value);
case XmlNodeType.CDATA:
Console.WriteLine("CDATA "+reader.Value);
case XmlNodeType.ProcessingInstruction:
Console.WriteLine("<?{0} {1}?>", reader.Name, reader.Value);
case XmlNodeType.Comment:
Console.WriteLine("<!--{0}-->", reader.Value);
case XmlNodeType.XmlDeclaration:
Console.WriteLine("<?xml version='1.0'?>");
case XmlNodeType.Document:
case XmlNodeType.DocumentType:
Console.WriteLine("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value);
case XmlNodeType.EntityReference:
case XmlNodeType.EndElement:
Console.Write("end element </{0}>", reader.Name);
if (reader.HasAttributes)
Console.WriteLine("Attributes of <" + reader.Name + ">");
while (reader.MoveToNextAttribute())
Console.WriteLine(" {0}={1}", reader.Name, reader.Value);
writer.WriteAttributeString(reader.Name, reader.Value);
catch (System.Exception ex)
private static void ValCallBack(object sender, ValidationEventArgs e)
Console.WriteLine("Validation Errors: {0}", e.Message);

~tata & take care~

Other Posts

No comments:

Post a Comment