tags:

views:

6811

answers:

4

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.

A: 

Try:

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

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

Edit: silly error

rjohnston
+1  A: 

I am not sure, but is it possible that your XPath query does not evaluate to a node set (this is, it is malformed)?

Look here for someone with a similar problem or here for an article on how to use text() in XPath queries. Maybe this might help you.

Mephisztoe
+1  A: 

The XPath expression contained a subtle error. 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!

Alex Angas
Did you came to this conclusion with the help of my links quoted above?
Mephisztoe
One of your links had the square bracket notation which I hadn't thought of using.
Alex Angas
+5  A: 

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