检查节点是否存在时,如何解决错误"表达式必须求值到节点集"?

时间:2020-03-06 14:58:15  来源:igfitidea点击:

我正在尝试使用以下.NET代码检查是否存在节点:

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

这总是会引起:

XPathException: Expression must evaluate to a node-set.

为什么会出现此错误,我该如何解决?谢谢你。

解决方案

尝试:

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

先前的表达式正在求值一个布尔值,该布尔值解释了异常错误。谢谢帮助!

给定的表达式的结果为布尔值,而不是节点集。我假设我们要检查ProjectName是否等于参数化的文本。在这种情况下,我们需要写

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

这为我们提供了符合给定条件的所有节点(节点集)的列表。该列表可能为空,在这种情况下,示例中的C#-Expression将返回null。

事后考虑:我们可以使用原始的xpath表达式,但不能与SelectSingleNode一起使用,而可以与Evaluate一起使用,如下所示:

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