Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use the XPath count expression to evaluate a if statement?

Tags:

java

xml

xpath

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?

like image 682
djangofan Avatar asked Dec 13 '22 00:12

djangofan


2 Answers

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

like image 112
Kennet Avatar answered Jan 01 '23 10:01

Kennet


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
like image 42
pb2q Avatar answered Jan 01 '23 10:01

pb2q