簡體   English   中英

在檢查節點是否存在時,如何解決錯誤“表達式必須評估到節點集”?

[英]How do I resolve the error “Expression must evaluate to a node-set” when checking for the existence of a node?

我正在嘗試使用以下.NET代碼檢查節點是否存在:

xmlDocument.SelectSingleNode(
        String.Format("//ErrorTable/ProjectName/text()='{0}'", projectName));

這總是提出:

XPathException:Expression必須求值為一個節點集。

為什么我會收到此錯誤,如何解決? 謝謝。

給定的表達式求值為布爾值,而不是節點集。 我假設您要檢查ProjectName是否等於參數化文本。 在這種情況下,你需要寫

//ErrorTable/ProjectName[text()='{0}']

這將為您提供與給定條件匹配的所有節點(節點集)的列表。 此列表可能為空,在這種情況下,示例中的C#-Expression將返回null。

作為事后的想法:你可以使用原始的xpath表達式,但不能使用SelectSingleNode,而是使用Evaluate,如下所示:

(bool)xmlDocument.CreateNavigator().Evaluate(String.Format("//ErrorTable/ProjectName/text()='{0}'", projectName));

嘗試:

Node node = xmlDocument.SelectSingleNode(String.Format("//ErrorTable/ProjectName = '{0}'", projectName));

if (node != null) {
    // and so on
}

編輯:愚蠢的錯誤

XPath表達式包含一個微妙的錯誤。 應該是:

xmlDocument.SelectSingleNode(String.Format("//ErrorTable/ProjectName[text()='{0}']", projectName));

前一個表達式正在評估一個布爾值,它解釋了異常錯誤。 謝謝您的幫助!

暫無
暫無

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

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