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

本文关键字:任何 结果 XML Asp net 读取 | 更新日期: 2023-09-27 18:32:36

我使用以下代码从此地址读取XML文件。

        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总是给我0.

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

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

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;
        }
我不知道

为什么它必须这么复杂,但是......

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);