Working with XMLTextWriter and XMLTextReader


XML (eXtensible Markup Language) is one of the most adopted and relative source to store the data and transport over the network because of its nature. Here I will be going over, how to write and Read XML source. There are numerous ways to work with XML like XML DOM, LINQ to XML and XML Stream approach.

Working with XMLTextWriter and XMLTextReader



XML (eXtensible Markup Language) is one of the most adopted and reliave source to store the data and transport over the network because of its nature. Here I will be going over, how to write and Read XML source. There are numereous ways to work with XML like XML DOM, LINQ to XML and XML Stream approach.

Here I will be working XML Stream approach i.e. XMLTextWriter and XMLTextReader. The XmlTextWriter provides a forward-only, read-only, non-cached way of generating XML streams, which helps you to build XML documents.

XMLTextWriter writes the data to XML as stream so it does not cached whole xml data I memory. Let take a small example here to write the Books object to XML file.
I have defined Book class with some properties and initializing data for book. The listing is shown below.

Books.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqToXML
{
class Books
{
public int ID { get;set; }
public string Name { get;set; }
public string PubId { get; set; }
public double Price { get; set; }

public List Init()
{
List books = new List
{
new Books{ID=1,Name="C# Simple", PubId="Pub#4567", Price=5000},
new Books{ID=2,Name="ASP.net Simple", PubId="Pub#4568", Price=6000},
new Books{ID=3,Name="ADO.net Simple", PubId="Pub#4569", Price=7000},
new Books{ID=4,Name="ASP.net MVC Simple", PubId="Pub#4590", Price=8000}
};
return books;
}
}
}


Now we have book object which will return the list of books from which want to create XML using stream approach. The listing is given below.

Writing to XML




private void writeXML()
{
TextWriter ioWritter = new StreamWriter(@"C:\XMLTestWrite.xml");

Books obj = new Books();
List lstBook = obj.Init();
var rootName = obj.GetType().Name;
string id = obj.GetType().GetProperty("ID").Name;
string name = obj.GetType().GetProperty("Name").Name;
string pubid = obj.GetType().GetProperty("PubId").Name;
string price = obj.GetType().GetProperty("Price").Name;

using (XmlTextWriter writer = new XmlTextWriter(ioWritter)){
writer.Formatting = Formatting.Indented;
writer.Indentation = 4;
writer.WriteStartDocument();
writer.WriteComment("List of Books from storage");
writer.WriteStartElement(rootName);
foreach (Books book in lstBook)
{
writer.WriteStartElement("Book");
writer.WriteAttributeString(id, book.ID.ToString());
writer.WriteElementString(name, book.Name);
writer.WriteElementString(pubid, book.PubId);
writer.WriteElementString(price, book.Price.ToString());
writer.WriteEndElement();
}
writer.WriteEndDocument();
};
ioWritter.Close();
}


It will create the xml file i.e. XMLTestWrite.xml with book information. As I mentioned it is stream appraoch so it will go through each xml element and create step by step. XMLTextWritter has rich set of methods which you can use to create Elements, Attributes, Comments, CDATA and so on.

Reading from XML


When you execute above function it will create the XML file. Now let's take a look how to read the same file which we just created using XMLTextReader. XMLTextReader is non-cached way of reading the XML Stream.
Below is the code which reads the xml file as stream and it reads from the starting to end of the file.


private String readXML()
{
StringBuilder builder = new StringBuilder();
using (XmlTextReader reader = new XmlTextReader(@"C:\XMLTestWrite.xml"))
{

while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Comment:
builder.Append("");
break;
case XmlNodeType.Element:
builder.Append("<" + reader.Name);
if (reader.HasAttributes)
{
while (reader.MoveToNextAttribute())
{
builder.Append(" " + reader.Name + "=" + reader.Value);
}
}
builder.Append(">");
break;
case XmlNodeType.Text:
builder.Append(reader.Value);
break;
case XmlNodeType.CDATA:
builder.Append("");
break;
case XmlNodeType.EndElement:
builder.Append("");
builder.AppendLine();
break;
}
}
reader.Close();
}
return builder.ToString();

}

Output




<?xml version="1.0" encoding="utf-8"?>
<!--List of Books from storage-->
<Books>
<Book ID="1">
<Name>C# Simple</Name>
<PubId>Pub#4567</PubId>
<Price>5000</Price>
</Book>
<Book ID="2">
<Name>ASP.net Simple</Name>
<PubId>Pub#4568</PubId>
<Price>6000</Price>
</Book>
<Book ID="3">
<Name>ADO.net Simple</Name>
<PubId>Pub#4569</PubId>
<Price>7000</Price>
</Book>
<Book ID="4">
<Name>ASP.net MVC Simple</Name>
<PubId>Pub#4590</PubId>
<Price>8000</Price>
</Book>
</Books>



Hope you will find this useful for better understanding for XMLTextWriter and XMLTextReader


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: