Simple XML Parser in C#

This article and the attached source code shows how to parse XML documents using .NET XML class library classes.

The application reads the XML file and then associates the xml tags to variables which are then displayed in a message box.

The namespace System.Xml would be the only additional namespace that we would be using.

Start of by initializing a new instance of the XmlDocument class.

  1. XmlDocument xDoc = new XmlDocument();  

Next use the load method to load the XML document from the specified stream.

  1. xDoc.Load("sampleXML.xml");  

Use the method GetElementsByTagName() to obtain the addresses of a collection of elements that match the specified name.

  1. XmlNodeList name = xDoc.GetElementsByTagName("myName");  
  2. XmlNodeList age = xDoc.GetElementsByTagName("myAge");  
XmlNodeList represents an ordered collection of nodes.

Display the results in a message box.

  1. MessageBox.Show("Name: " + name[0].InnerText);  
InnerText will return the concatenated values of the node and all its children.


Similar Articles