65.9K
CodeProject is changing. Read more.
Home

Simple C# XML Parser

starIconstarIconemptyStarIconemptyStarIconemptyStarIcon

2.00/5 (6 votes)

Sep 25, 2006

CPOL
viewsIcon

63335

downloadIcon

738

Simple XML parser for C# for those who are used to the ways of libxml2 or Expat.

Introduction

This is a very simple XML parser written for C# for people who are used to using the callbacks of libxml2 and Expat, such as: OnElementStart, OnElementEnd, and OnData.

It is quite simple to use as it uses delegates and events.

Start off by adding the XmlParser.cs file to your project and creating an XmlParser object.

XmlParser xp = new XmlParser();

Next, start to fill in the events.

xp.OnElementStart += new OnElementStartD(xp_OnElementStart);
xp.OnElementEnd += new OnElementEndD(xp_OnElementEnd);
xp.OnElementData += new OnElementDataD(xp_OnElementData);

VC# will do most of the work for you with tab complete; if it doesn't, create the following functions:

void xp_OnElementData(string name, string CData)
{
    throw new Exception("The method or operation is not implemented.");
}

void xp_OnElementEnd(string name)
{
    throw new Exception("The method or operation is not implemented.");
}

void xp_OnElementStart(string name, string ns, int numAttribs, Array attribs)
{
    throw new Exception("The method or operation is not implemented.");
}

Then, replace the exceptions with whatever code you want to, to parse the XML code.

Lastly, under where you filled in the events, do something like:

xp.Load(myXmlFile);
xp.Parse();

Happy XML parsing!