所以我有一个看起来像这样的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="2010-05-28">
<Cube currency="USD" rate="1.2384"/>
<Cube currency="JPY" rate="113.06"/>
</Cube>
<Cube time="2010-05-27">
<Cube currency="USD" rate="1.2255"/>
<Cube currency="JPY" rate="110.79"/>
</Cube>
</Cube>
</gesmes:Envelope>现在假设我有一个指向<Cube time="2010-05-28">节点的XmlNode timeNode和一个指向加载的<Cube time="2010-05-28">文档的document。假设我需要通过调用一个SelectSingleNode(string xpath)方法来获取<Cube currency=USD" rate="1.2384"/>节点中rate属性的值。
到目前为止,我能想出这样的代码:
XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable);
nsmgr.AddNamespace("ecb", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");
nsmgr.AddNamespace("gesmes", "http://www.gesmes.org/xml/2002-08-01");
XmlNode currencyNode = timeNode.SelectSingleNode("descendant::ecb:Cube[@ecb:currency='USD']", nsmgr);
string rate = currencyNode.Attributes.GetNamedItem("rate").Value;这里的问题是currencyNode在这里设置为null。我检查了timeNode,它指向了正确的节点,所以我猜问题出在SelectSingleNode方法中的路径上,但是我看不出问题出在哪里。我已经查看了其他有类似问题的帖子,但找不到任何可以解决地雷的东西。任何指针都将不胜感激。
发布于 2010-08-01 21:22:28
默认情况下,XML属性没有名称空间,因此您不需要在它们上使用名称空间前缀。试试看:
XmlNode currencyNode = timeNode.SelectSingleNode("descendant::ecb:Cube[@currency='USD']", nsmgr);您也不需要在这里显式指定子代轴,因为默认情况下它将查看子代,因此您也可以将其缩短为:
XmlNode currencyNode = timeNode.SelectSingleNode("ecb:Cube[@currency='USD']", nsmgr);发布于 2010-08-01 21:31:14
将xpath更改为
descendant::ecb:Cube[@currency="USD"]https://stackoverflow.com/questions/3382140
复制相似问题