How to read XML using the XmlDocument Class

Before you can use the XmlDocument class, you have to add a reference to the System.Xml namespace. This namespace provides standards-based support for processing XML.

using System.Xml;

After adding the reference, it’s possible to initialize a new instance of the XmlDocument class. This class has the Load method to load a XML document from a specified stream, URL, TextReader class or XmlReader class.

In my example, I will use a URL to the XML file. This URL can be either a local path to a file or an HTTP Web adress.

After loading the xml file, use the GetElementsByTagName method to obtain a collection of XML nodes that match the specified element name.

Now you have to iterate this collection.

For getting the data of a specific node, I use the SelectSingleNode method. This method selects the first XmlNode that matches the specified element name. The InnerXml property will return the concatenated values of the node.
To get a specific attribute value, use the Attributes property with the specified attribute name. The Attributes property returns a collection with all the attributes of the node.

Example: Cars.xml

<?xml version="1.0" encoding="utf-8"?>
  <car marque="Audi">
    <model>A4 2.0 TDI</model>
    <emissions>115 CO2</emissions>
    <weight>1550 kg</weight>
    <speed>215 km/h</speed>
  <car marque="BMW">
    <emissions>119 CO2</emissions>
    <weight>1495 kg</weight>
    <speed>235 km/h</speed>
XmlDocument doc = new XmlDocument();

XmlNodeList cars = doc.GetElementsByTagName("car");

foreach (XmlNode car in cars)
  string marque = car.Attributes["marque"].Value;
  string model = car.SelectSingleNode("model").InnerXml;
  string speed = car.SelectSingleNode("speed").InnerXml;

  Console.WriteLine(string.Format("{0}: {1} - {2}", marque, model, speed));


Audi: A4 2.0 TDI - 215 km/h
BMW: 320d - 235 km/h

Comments are closed.

%d bloggers like this: