Friday, June 26, 2009

C# XML Parser

There is no need to have any third party DLL to parse XML document in C#.
Parse.cs is simple code to parse any xml document.

Download Source Code

Parser.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Collections;
using System.Web.UI.WebControls;

///
/// RTv4 Parser for Parsing Bank Services.
/// It also contains general purpose function for parsing XML files.
///

public class Parser
{
private List serviceList = null;

public Parser()
{
}

public List parse()
{
serviceList = new List();
bool newService = true;
String Tag = "";
Service service = null;
Node node = null;
XmlTextReader reader = null;
string sPath = HttpContext.Current.Server.MapPath(@"App_Code\Config\check.xml");

try
{
reader = new XmlTextReader(sPath);

while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:

Hashtable attributes = new Hashtable();
string strURI = reader.NamespaceURI;
string strName = reader.Name;

if (strName.Equals("service") && newService)
{
service = new Service();
newService = false;
}

if (strName.Equals("Field"))
{
node = new Node();
}

if (strName.Equals("Label"))
{
Tag = "Label";
}
else if (strName.Equals("DataType"))
{
Tag = "DataType";
}

if (reader.HasAttributes)
{
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);

if (reader.Name.Equals("IDS"))
{
service.serviceID = reader.Value;
}
if (reader.Name.Equals("Name"))
{
service.serviceName = reader.Value;
}

if (reader.Name.Equals("ID"))
{
node.nodeID = reader.Value;
}
}
}
break;

case XmlNodeType.EndElement:

if (reader.Name.Equals("Field"))
{
service.nodeList.Add(node);
}

if (reader.Name.Equals("service"))
{
newService = true;
serviceList.Add(service);
}

break;

case XmlNodeType.Text:

if (Tag.Equals("Label"))
{
node.label = reader.Value;
}
else if (Tag.Equals("DataType"))
{
node.dataType = reader.Value;
}

break;

default:
break;
}
}
}
catch (XmlException e)
{
Console.WriteLine("error occured: " + e.Message);
}
finally
{
reader.Close();
}

return serviceList;
}

}

Sample XML used in this example.