XSLT is a powerful tool and I'm planning to use it for creating some standard forms and emails in JavaHotel application. For instance: to send booking confirmation to the customer. To keep all stuff simple I'd like to send a text (not html) email. But even in the text email it were nice to have some simple formatting:
Night Adults Daily Rate 2014/03/01 2 77 EUR 2014/03/02 2 77 EUR 2014/03/03 2 77 EUR -------------------------------- Total: 231 EUR
But unfortunately XSLT does not contain anything like 'padding-left' or 'padding-right' function.
Xalan XSLT processor available in JSE Sun Java is 1.0 (I'd like to avoid additional dependencies) so one cannot use XSLT 2.0 features like XPath 2.0 function library or xsl:function (a huge library is available here).
So the only solution is to create a custom padding functions.
XSLT java function enhancement
It is not easy being on short notice to grasp how to create custom Java function for XSLT. What's more - there are differences between Apache Xalan and Saxon. But after picking the essentials everything runs smoothly.
There are two simple ways to declare Java enhancement in XSLT document (very useful link).
The first requires full qualified (with package) Java class name.
<xsl:template name="currentTime" xmlns:java="http://xml.apache.org/xslt/java"> <xsl:value-of select="java:java.util.Date.new()"> </xsl:value-of></xsl:template>The second method: the prefix is bound to a specific class and function name can be qualified by namespace only.
<xsl:template name="currentTime" xmlns:date="java://java.util.Date"> <xsl:value-of select="date:new()"/> </xsl:template>Solution
After passing this Rubicon I created a simple application to have output like that:
----------------------------------------------------------------- Description Unit Price Qty Amount ----------------------------------------------------------------- AMD Athlon 580.00 6 3480.00 PDC-E5300 645.00 4 2580.00 LG 18.5" WLCD 230.00 10 2300.00 HP LaserJet 5200 1100.00 1 1100.00 ----------------------------------------------------------------- Total 9460.00Full source code is available here (Java Main, xslt template, test input file and Java custom library).
Java function code is extremely simple and straightforward.
public class MyFun { public static String upperCase(String s) { return s.toUpperCase(); } public static String fillString(int length, String s) { StringBuffer b = new StringBuffer(); for (int i = 0; i < length; i++) b.append(s.charAt(0)); return b.toString(); } public static String paddingLeft(int padd, String s) { if (s.length() >= padd) return s; return fillString(padd - s.length(), " ") + s; } public static String paddingRight(int padd, String s) { if (s.length() >= padd) return s; return s + fillString(padd - s.length(), " "); } }
Brak komentarzy:
Prześlij komentarz