.net 在检查节点是否存在时,如何解决错误“表达式必须评估为节点集”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/157044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 10:11:24  来源:igfitidea点击:

How do I resolve the error "Expression must evaluate to a node-set" when checking for the existence of a node?

.netxmlxpath

提问by Alex Angas

I'm attempting to check for the existence of a node using the following .NET code:

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

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

This always raises:

这总是引发:

XPathException: Expression must evaluate to a node-set.

XPathException:表达式必须计算为节点集。

Why am I getting this error and how can I resolve it? Thank you.

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

回答by TToni

The expression given evaluates to a boolean, not a node-set. I assume you want to check whether the ProjectName equals the parametrized text. In this case you need to write

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

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

This gives you a list of all nodes (a nodeset) matching the given condition. This list may be empty, in which case the C#-Expression in your sample will return null.

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

As an afterthought: You canuse the original xpath expression, but not with SelectSingleNode, but with Evaluate, like this:

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

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

回答by rjohnston

Try:

尝试:

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

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

Edit: silly error

编辑:愚蠢的错误

回答by Alex Angas

The XPath expression contained a subtle error. It should have been:

XPath 表达式包含一个微妙的错误。本来应该是:

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

The previous expression was evaluating to a boolean, which explains the exception error. Thanks for the help!

前面的表达式计算结果为布尔值,这解释了异常错误。谢谢您的帮助!