I'm trying to figure out how to use a Xpath expression to verify that there is only one matching node in an XPath expression. Here is some sample XML:
<a>
<b>
<c>X:1 Y:0</c>
<c>X:1 Y:0</c>
<c>X:2 Y:0</c>
</b>
<b>
<c>X:1 Y:0</c>
<c>X:2 Y:0</c>
</b>
</a>
So, I tried code similar to this, but it doesn't work:
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
try {
XPathExpression expr = xpath.compile( "count(//a/b/c)" ) );
} catch ( XPathExpressionException e ) {
printErr( e );
}
if ( expr == true ) {
// edit XML node
}
There is supposedly a way for the count expression to return a Boolean = true . How do I get this?
Maybe something like this:
XPathExpression xpr = xpath.compile("count(//a/b/c)");
System.out.println(xpr.evaluate(n, XPathConstants.NUMBER));
xpr = xpath.compile("count(//a/b/c) = 5");
System.out.println(xpr.evaluate(n, XPathConstants.BOOLEAN));
where n is a Node/Element from your document
First prints 5.0, second prints true
You've only compiled an XPath expression, you haven't actually evaluated it.
Note that you can evaluate the expression directly using XPath.evaluate()
:
result = xpath.evaluate("count(//a/b/c)", input);
Or using your pre-compiled expr
:
result = expr.evaluate(input);
And that these evaluate
methods can also take as an additional argument a type, such as XPathConstants.BOOLEAN
.
So this will work, with input
as an InputSource
for your XML:
XPathExpression expr = xpath.compile("count(//a/b/c) = 5");
Object retval = expr.evaluate(input, XPathConstants.BOOLEAN);
if ((Boolean) retval)
// edit XML node
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With