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

.net, xml, xpath

Solution

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

//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.

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

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

Problem

I'm attempting to check for the existence of a node using the following .NET code: ``` xmlDocument.SelectSingleNode( String.Format("//ErrorTable/ProjectName/text()='{0}'", projectName)); ``` This always raises: XPathException: Expression must evaluate to a node-set. Why am I getting this error and how can I resolve it? Thank you.

Original source