[英]Why my XPath request to XML file on web doesn't work?
有一個XML文件,其匯率為http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml :
<gesmes:Envelope>
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:Sender>
<gesmes:name>European Central Bank</gesmes:name>
</gesmes:Sender>
<Cube>
<Cube time="2009-11-26">
<Cube currency="USD" rate="1.5071"/>
...
我執行下一個XPath請求:
var doc = new XmlDocument();
doc.Load(url);
var node = doc.SelectSingleNode("//Cube[@currency=\"USD\""]);
var value = node.Attributes["rate"].Value;
但它返回null
! 我的錯誤在哪里?
如果我執行此請求,則一切正常:
var node = dic.SelectSingleNode("//*[@currency=\"USD\"]");
var name = node.Name; // "Cube"
問題是名稱空間。 如果可以使用LINQ to XML,則可以非常輕松地表達此查詢。 否則,它會有些棘手-您需要這樣的東西:
var doc = new XmlDocument();
doc.Load(url);
XPathNavigator navigator = doc.CreateNavigator();
XmlNamespaceManager nsMgr = new XmlNamespaceManager(nav.NameTable);
nsMgr.AddNamespace("gesmes", "http://www.gesmes.org/xml/2002-08-01");
nsMgr.AddNamespace("ns0", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");
var node = doc.SelectSingleNode("//ns0:Cube[@currency=\"USD\""], nsMgr);
var value = node.Attributes["rate"].Value;
(您實際上並不需要管理器中的gesmes命名空間,但是如果您需要查找任何其他元素,它將變得更容易。)
編輯:Peter Murray-Rust的答案是一個不錯的選擇-您采用哪種方法取決於您希望元素能夠找到的具體程度。 如果只需要一個查詢的名稱空間,就可以在XPath中直接包含URI。 如果您不僅僅需要它,還可以使用名稱空間管理器獲得更簡潔的查詢。
嘗試
var node = doc.SelectSingleNode("//*[local-name()='Cube' and @currency=\"USD\""]);
您可以隨時添加名稱空間
var node = doc.SelectSingleNode("//*[local-name()='Cube' and
namespace-uri()='http://www.ecb.int/vocabulary/2002-08-01/eurofxref' and
@currency=\"USD\""]);
盡管遇到了很大的麻煩,但我還是更喜歡嘗試整理名稱空間前綴。 而且還避免了默認名稱空間的問題(xmlns="")
XPathVisualizer可以派上用場。 免費。 它不會告訴您使用名稱空間,但是它將在UI中將名稱空間放在您的面前,並且可以讓您真正快速地測試一堆替代方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.