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 :

<EmployeeList>
<Company ID="1">
<Employee>Employee11</Employee>
<Employee>Employee12</Employee>
<Employee>Employee13</Employee>
</Company>
<Company ID="2">
<Employee>Employee21</Employee>
<Employee>Employee22</Employee>
<Employee>Employee23</Employee>
</Company>
<Company ID="3">
<Employee>Employee31</Employee>
<Employee>Employee32</Employee>
<Employee>Employee33</Employee>
<Employee>Employee34</Employee>
</Company>
</EmployeeList>


The schema file generated using XSD.exe tool is :

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


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)
{
try
{
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);
writer.WriteStartElement(reader.Name);
break;
case XmlNodeType.Text:
Console.WriteLine("text "+reader.Value);
writer.WriteString(reader.Value);
break;
case XmlNodeType.CDATA:
Console.WriteLine("CDATA "+reader.Value);
break;
case XmlNodeType.ProcessingInstruction:
Console.WriteLine("<?{0} {1}?>", reader.Name, reader.Value);
break;
case XmlNodeType.Comment:
Console.WriteLine("<!--{0}-->", reader.Value);
break;
case XmlNodeType.XmlDeclaration:
Console.WriteLine("<?xml version='1.0'?>");
break;
case XmlNodeType.Document:
break;
case XmlNodeType.DocumentType:
Console.WriteLine("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value);
break;
case XmlNodeType.EntityReference:
Console.Write(reader.Name);
break;
case XmlNodeType.EndElement:
Console.Write("end element </{0}>", reader.Name);
writer.WriteEndElement();
break;
}
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);
}
}
}
writer.Flush();
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
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