2011-07-27 37 views
4

我正在读取远程XML文件,并且一旦将XML加载到XMLDocument对象中,我需要遍历它并提取我的应用程序需要的值。我的代码如下:在C中读取远程XML#

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 

但是我得到的问题是,总是XmlNodeList中返回零个节点,而如果我在XMLSpy的计算XPath表达式我得到我需要的节点。

对于引用的XML看起来像:

<?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> 

我想回到立方体节点的美元和英镑。

任何想法你聪明的人?

感谢 铝

回答

12

虽然你绝对可以XmlDocument API中的命名空间和XPath的工作,我会强烈建议您使用的LINQ to XML(.NET 3.5),如果可能的话:

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); 
} 
+0

聪明聪明 - 我将如何循环通过结果? Linq还不是很好! – higgsy

+0

@higgsy:编辑显示结果。 –

+0

现货,很好的解决方案 - 非常感谢! – higgsy