65.9K
CodeProject is changing. Read more.
Home

XML parsing in C#

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.66/5 (27 votes)

May 30, 2002

viewsIcon

198342

downloadIcon

2816

This project gives you a head start to write an XML parser in C#.

Introduction

This project gives you a head start to write an XML parser in C#. The important namespace to achieve our goal is System.Xml. Though you might find it strange, unlike other languages/class libraries their are no direct functions like startElement and endElement to your rescue. You will have to manage all this on your own. So let's start looking at this important block of the code

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 is XmlTextReader. XmlTextReader provides forward-only, read-only access to a stream of XML data. The current node refers to the node on which the reader is positioned. The reader is advanced using any of the read methods and properties reflect the value of the current node. Note that we cache the element name before we move to the attributes.

The NodeType property of XmlTextReader gets the type of the current node. Accordingly we process the node and call necessary functions on it.

You can forward me your comments at lparam@hotmail.com