This article is currently in the process of being translated into Spanish (~25% done).


Reading XML with the XmlReader class

Existen principalmente dos métodos para leer XML con C#: con la clase XmlDocument y con la clase XmlReader. XmlDocument lee el contenido completo del XML en memoria y te permite navegar hacia adelante y atrás como lo necesites, o incluso consultar (query) al documento usando la tecnología XPath.

XmlReader es una alternativa más rápida y que consume menos memoria. Te permite recorrer el contenido del XML, un elemento a la vez mientras te permite ver el valor, y después se mueve al siguiente elemento. Al hacerlo así, obviamente consume muy poca memoria porque solo mantiene un elemento a la vez, y como tienes que comprobar manualmente los valores, solo obtendrpas kis ekenebtis relevantes haciéndolo muy rápido. En este capítulo, nos enfocaremos en la clase XmlReader, después veremos la clase XmlDocument en el siguiente capítulo.

Let's try a little example, where we read an XML document containing currency rates. Fortunate for us, the European Central Bank has one that we can use. We could download it and read it from the harddrive, but actually, both the XmlReader and the XmlDocument classes can read XML from a remote URL just as well as from a local file. You can see the XML here ( and here comes some code and then an explanation of it:

using System;
using System.Text;
using System.Xml;

namespace ParsingXml
    class Program
        static void Main(string[] args)
            XmlReader xmlReader = XmlReader.Create("");
                if((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "Cube"))
                        Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));                    

We start off by creating the XmlReader instance, using the static Create() method. It has several overloads, but the simplest of them just takes a URL pointing to the file. In a while loop, we call the Read() method on the XmlReader instance. It advances the reader to the next element and then returns true as long as there is more to read. Inside the loop, we can now use one of the many properties and methods on the XmlReader to access data from the current element.

In our case, we check the NodeType to see if we have an Element (the tag part), and if the name is "Cube". As you can see in the XML document we used, each currency rate is within an element called Cube, so this is of course what we're looking for - the rest is ignored. Once we have a Cube element, we do a formal check to see if it has attributes (which it should) and then we use the GetAttribute() method to read the two attribute values "currency" and "rate". We print them out to the Console and then we move on to the next element. The result should be a complete list of currencies and their current exchange rate.

As you can see, this is pretty simple to do, but mainly because we just need the data in the same order as they are read, without doing anything fancy to it. In the next chapter, we will do the same thing but using the XmlDocument class, so that you can see the difference.

Note: You should be aware that there are many ways in which the above code could fail and throw an exception, which you should of course handle. See the chapter on exceptions for more information.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!