Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading remote XML in C#

Tags:

c#

xml

asp.net

I'm reading a remote XML file and once the XML is loaded into an XMLDocument object I need to traverse through it and extract the values that my application requires. My code is as follows:

    XmlDocument xmlDocument = new XmlDocument();
    xmlDocument.Load("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");

    XmlNamespaceManager nsMan = new XmlNamespaceManager(xmlDocument.NameTable);
    nsMan.AddNamespace("gesmes", "http://www.gesmes.org/xml/2002-08-01");
    nsMan.AddNamespace("", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");


    XmlNodeList xmlNodeList = xmlDocument.DocumentElement.SelectNodes("/gesmes:Envelope/Cube/Cube/Cube", nsMan);

    HttpContext.Current.Response.Write("The numner of nodes is " + xmlNodeList.Count); //it's always zero

However the problem I'm getting is that XmlNodeList always returns zero nodes, whereas if I evaluate the XPath expression in XMLSpy I get the nodes I require.

For reference the XML looks like:

<?xml version="1.0" encoding="UTF-8"?>
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:Sender>
    <gesmes:name>European Central Bank</gesmes:name>
</gesmes:Sender>
<Cube>
    <Cube time='2011-07-27'>
        <Cube currency='USD' rate='1.4446'/>
        <Cube currency='GBP' rate='0.88310'/>
    </Cube>
</Cube>
</gesmes:Envelope>

I want to return the Cube nodes for USD and GBP.

Any ideas you clever people?

Thanks Al

like image 880
higgsy Avatar asked Dec 12 '22 10:12

higgsy


1 Answers

While you definitely can work with namespaces and XPath in the XmlDocument API, I would strongly advise you to use LINQ to XML (.NET 3.5) if at all possible:

string url = "http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml";
XDocument doc = XDocument.Load(url);

XNamespace gesmes = "http://www.gesmes.org/xml/2002-08-01";
XNamespace ns = "http://www.ecb.int/vocabulary/2002-08-01/eurofxref";

var cubes = doc.Descendants(ns + "Cube")
               .Where(x => x.Attribute("currency") != null)
               .Select(x => new { Currency = (string) x.Attribute("currency"),
                                  Rate = (decimal) x.Attribute("rate") });

foreach (var result in cubes)
{
    Console.WriteLine("{0}: {1}", result.Currency, result.Rate);
}
like image 116
Jon Skeet Avatar answered Dec 24 '22 13:12

Jon Skeet