vikram keshari
vikram keshari

Reputation: 73

how to execute java functions in xslt

I am trying to get the date using java namespace in XSLT file, and minus X no of days from it. How to minus days from from date in xslt?

I tried using java namespace to get the current date and use the java.time.LocalDate.now().minusDays(2) the days. It works fine in java but in xslt it fails

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
                              xmlns:xs="http://www.w3.org/2001/XMLSchema"
                              xmlns:java="http://xml.apache.org/xslt/java" 
                              xmlns:xalan="http://xml.apache.org/xalan"
                              xmlns:fn="http://www.w3.org/2005/xpath-functions"
                              xmlns:datetime="http://exslt.org/dates-and-times"
                              xmlns:math="http://exslt.org/math"
                              xmlns:date="http://www.date.org/"
                              xmlns:exslt="http://exslt.org/common"
                              xmlns:js="javascript:code"
                              exclude-result-prefixes="java"
                              extension-element-prefixes="mcr">

    <xsl:variable name="test" select="java:java.time.LocalDate.now().minusDays(2)"/>

when I am using only "java:java.time.LocalDate.now()" in select, I am getting today's date as output. Only the minusDays() function doesn't seem to work.

I am expecting an output which is currentDate minus 2 days in yyyy-MM-dd format. Ex : if today's Date is 12 June, 2019 OUTPUT : 2019-06-10

Upvotes: 0

Views: 533

Answers (1)

Michael Kay
Michael Kay

Reputation: 163262

This is a valid XPath function call: java:java.time.LocalDate.now(), which Xalan interprets as a call on an external Java static method.

You then follow this with ".". But "." is not a valid operator in XPath. If you want to apply one XPath function F() to the result of another function G(), you can't use the Java syntax F().G(), you have to use the XPath syntax G(F()). And that means you'll need to use the fully-qualified function name corresponding to minusDays().

Since you're in Java, you could switch to Saxon, which supports all the date-and-time functions built in to XSLT 2.0, so all this calling out to Java for simple date/time arithmetic becomes unnecessary.

Upvotes: 1

Related Questions