2

can we use tokenize function in XPath

The general java code i use to process XSLT and XML files are :

XPath xPath = XPathFactory.newInstance().newXPath();
InputSource inputXML = new InputSource(new StringReader(xml));
String expression = "/root/customer/personalDetails[age=tokenize('20|30','|')]/name";
boolean evaluate1 = (boolean) xPath.compile(expression).evaluate(inputXML, XPathConstants.BOOLEAN);

XML :-

<?xml version="1.0" encoding="ISO-8859-15"?>
<root>
    <customer>
        <personalDetails>
            <name>ABC</name>
            <value>20</value>
        </personalDetails>
        <personalDetails>
            <name>XYZ</name>
            <value>21</value>
        </personalDetails>
        <personalDetails>
            <name>PQR</name>
            <value>30</value>
        </personalDetails>
    </customer>
</root>

Expected Response :- ABC,PQR

  • Your xslt does not match the xml (`age` vs `value`). Regarding the tokenize: `tokenize` returns a sequence of strings, can you really compare that using `=`? – f1sh Jan 04 '22 at 11:29
  • `tokenize` is part of XPath 2 and later so the default JAXP XPath API which tends to implement only XPath 1 doesn't support it. Saxon 9 or 10, however, can be used in Java, to have XPath 3 support. It is not recommended to do it using the JAXP API, in particular if you want results that don't fit that API. Your code is unclear, it seems, assuming XPath 2, you just want `/root/customer/personalDetails[value=(20, 30)]/name` but of course as a node list not as a boolean. – Martin Honnen Jan 04 '22 at 13:36

1 Answers1

1

Yes, you can use the tokenize() function in XPath, provided your XPath processor supports XPath 2.0 or later.

For Java, the popular choice of XPath 2.0+ processor is Saxon.

You can use the JAXP API with Saxon, however, it's not really designed to work well with XPath 2.0+, so it's preferable to use Saxon's own API (called s9api).

For this particular example, you don't need tokenize(). In XPath 2.0+ you can write

[age=('20', '30')]

Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
Michael Kay
  • 156,231
  • 11
  • 92
  • 164