Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a boolean from an XPath expression

Tags:

.net

xpath

We would like to implement existance checks of elements via XPath expression. The XPath expressions are defined externally. We are trying to use the XPathEvaluate extension method from System.Xml.XPath, but it complains when we try to do the following.

XDocument d = new XDocument(
                new XElement("test", 
                    new XElement("element"),
                    new XElement("element")));
bool b = (bool)d.XPathEvaluate("/test/element[exists()]");

This function currently fails with an exception "Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.". We get the same message if we try exists(/test/element).

One of the other things that we would like to express in an XPath expression is the number of elements, e.g. count(/text/element) = 2.

The testing condition should be part of the XPath expression.

The function call d.XPathEvaluate("/test/element[last()]") evaluates as expected.

Is it possible to use XPathEvaluate this way?

[Edit] Yes.

If not, are there any alternatives in the .Net framework?

[Edit] Yes.

[Edit] Remaining question: why doesn't the exists function work?

like image 904
Jeroen Huinink Avatar asked Feb 26 '26 21:02

Jeroen Huinink


2 Answers

Have you tried the XPath:

boolean(/test/element)
like image 157
Santiago Cepas Avatar answered Mar 03 '26 17:03

Santiago Cepas


After some more experimenting, it seems like I answered my own question.

Of course you can do count(/test/element) > 0 as an exists check. (And we were looking at this with three people :-( )

bool b = (bool)d.XPathEvaluate("count(/test/element) > 0");
like image 25
Jeroen Huinink Avatar answered Mar 03 '26 17:03

Jeroen Huinink



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!