XML Parser in C#
This project gives you a head start to writeXML parser in C#. The important namespace to achieve our goal would beSystem.Xml. Though you might find it strange, unlike otherlanguages/class libraries their are no direct functions likestartElement and endElement at your rescue. You will have to manage allthis on your own. So lets start looking at this important block of thecode
void ParseURL(string strUrl)
{
try
{
XmlTextReader reader = new XmlTextReader(strUrl);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
Hashtable attributes = new Hashtable();
string strURI= reader.NamespaceURI;
string strName= reader.Name;
if (reader.HasAttributes)
{
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
attributes.Add(reader.Name,reader.Value);
}
}
StartElement(strURI,strName,strName,attributes);
break;
//
//you can handle other cases here
//
//case XmlNodeType.EndElement:
// Todo
//case XmlNodeType.Text:
// Todo
default:
break;
}
}
catch (XmlException e)
{
Console.WriteLine("error occured: " + e.Message);
}
}
As we see the main class here isXmlTextReader. XmlTextReader provides forward-only, read-only access toa stream of XML data. The current node refers to the node on which thereader is positioned. The reader is advanced using any of the readmethods and properties reflect the value of the current node. Note thatwe cache the element name before we move to the attributes.
NodeType property of XmlTextReader gets thetype of the current node. Accordingly we process the node and callnecessary functions on it.
Download CSParser.zip
You can forward me your comments at lparam@hotmail.com




09. Sep, 2006 by 







No comments yet... Be the first to leave a reply!