TOC

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

XML:

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 ( http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml) 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("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
            while(xmlReader.Read())
            {
                if((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "Cube"))
                {
                    if(xmlReader.HasAttributes)
                        Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));                    
                }
            }
            Console.ReadKey();
        }
    }
}

Empezamos creando la instancia XmlReader, usando el metodo Create(); este tiene muchas opciones, pero solo usaremos una de ellas que es apuntar a una URL. Usaremos un ciclo While para llamar al metodo Read, esto avanzara la lectura al siguiente elemento siempre que exista mas que leer, ahora podemos usar muchas propiedades y metodos sobre el XmlReader para accesar a los datos del actual elemento.

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!