[英]How do I resolve the error “Expression must evaluate to a node-set” when checking for the existence of a node?
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:Expression必须求值为一个节点集。
Why am I getting this error and how can I resolve it? 为什么我会收到此错误,如何解决? Thank you.
谢谢。
The expression given evaluates to a boolean, not a node-set. 给定的表达式求值为布尔值,而不是节点集。 I assume you want to check whether the ProjectName equals the parametrized text.
我假设您要检查ProjectName是否等于参数化文本。 In this case you need to write
在这种情况下,你需要写
//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 can use 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));
Try: 尝试:
Node node = xmlDocument.SelectSingleNode(String.Format("//ErrorTable/ProjectName = '{0}'", projectName));
if (node != null) {
// and so on
}
Edit: silly error 编辑:愚蠢的错误
The XPath expression contained a subtle error. XPath表达式包含一个微妙的错误。 It should have been:
应该是:
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!
谢谢您的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.