在Asp.net中读取XML没有得到任何结果

时间:2016-01-29 15:03:26

标签: c# asp.net

我使用以下代码从this address读取XML文件。

fn("abc", "def")

问题是我没有得到任何东西。 XmlDocument xdoc = new XmlDocument(); xdoc.Load("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"); XmlNodeList nodeList = xdoc.DocumentElement.SelectNodes("//gesmes/Cube/Cube"); if (nodeList == null) lblOutput.Text = "node is null"; foreach (XmlNode node in nodeList) { XmlNode innerNode = node.SelectSingleNode(".//Cube"); lblOutput.Text = innerNode.Attributes["currency"].Value; } 总是给我nodeList.Count

2 个答案:

答案 0 :(得分:2)

您需要正确处理命名空间。 可能有多种方法来处理它们,这是一个

XmlDocument xdoc = new XmlDocument();
        xdoc.Load("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
        XmlNamespaceManager xnm = new XmlNamespaceManager(xdoc.NameTable);
        xnm.AddNamespace("gesmes", "http://www.gesmes.org/xml/2002-08-01");
        xnm.AddNamespace("eurofxref", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");

        XmlNodeList nodeList = xdoc.DocumentElement.SelectNodes("//gesmes:Envelope/eurofxref:Cube/eurofxref:Cube", xnm);

        if (nodeList == null)
        { 
            var text = "node is null";
        }
        foreach (XmlNode node in nodeList)
        {
            XmlNode innerNode = node.SelectSingleNode(".//eurofxref:Cube", xnm);

            var text = innerNode.Attributes["currency"].Value;
        }

答案 1 :(得分:1)

我不知道为什么它必须这么复杂但......

XmlDocument xdoc = new XmlDocument();

xdoc.Load("https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

XmlNamespaceManager xMan = new XmlNamespaceManager(xdoc.NameTable);

xMan.AddNamespace("def", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");

XmlNodeList nodeList = xdoc.DocumentElement.SelectNodes("//def:Cube", xMan);