簡體   English   中英

如何在C#中結合兩個XPath查詢

[英]How to combine two XPath queries in C#

我試圖通過XPath評估檢查XML文檔中的兩個規則。

規則是:

  • /根/ PATH1 /文本()= 'TABLE1'
  • /根/ PATH2 /文本()= 'TABLE2'

我的代碼如下:

XPathDocument document = new XPathDocument(myDocument);
XPathNavigator navigator = document.CreateNavigator();
XmlNamespaceManager xpathNsMgr = new XmlNamespaceManager(navigator.NameTable);    
xpathNsMgr.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
var result = (bool)navigator.Evaluate("((/root/path1/text()='TABLE1') and (/root/path2/text()='TABLE2'))", xpathNsMgr);

如果我通過評估兩個XPath來檢查它們自己,那么一切正常。 但是,如果按照上面的代碼所示將它們組合檢查,則會收到以下錯誤:

xsltcontext is needed for this query because of an unknown function

為什么不能將兩個XPath結合在一起並進行評估? 我認為自XPath 1.0起,“和”,“或”等都是有效的運算符...

.NET XPathNavigator僅支持XPath 1.0。

您可以通過將條件變成謂詞(方括號)來輕松建模檢查,並查看結果節點集是否為空。

var result = navigator.Evaluate("/*[path1 = 'TABLE1' and path2 = 'TABLE2']", xpathNsMgr);

/*在此選擇文檔元素。 如果document元素的實際名稱很重要,請改寫/root

如@Tomalak和@Martin Honnen所述,XPath 1.0並未完​​全支持我的條件。 諸如existant()之類的功能是XPath 2.0的一部分。

由於.NET 4.5(我必須使用)不支持XPath 2.0,因此我使用以下Nuget包來解決我的問題: https ://www.nuget.org/packages/XPath2/

只需更換

navigator.Evaluate(...

navigator.XPath2Evaluate(...

並且可以評估表達式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM