How to write xslt extended method? Can you give an example?
Created May 7, 2012
Roseanne Zhang What you want to do does not even require a customized java extention. Simply using java.util.Date is enough. However, if you want to format you date string properly, then you do need to write your own class.
I found some time, and wrote 2 examples. One does what you wanted to do. The other does more.
- A simple Java extension example
You can apply it to any well-formed XML file. It is not a very good practice, since you must use transformer knowing Java. The better practice would be using Microsoft msxml. However, I need to learn it before giving an example.The next FAQ allows you to change the date string format in your XSLT. <h5>XSLT sourece </h5>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:java="java"> <!-- add a today-date to your XML under the root --> <xsl:template match="/*"> <xsl:element name="{name(.)}"> <today-date> <xsl:value-of select="java:util.Date.new()" /> </today-date> <xsl:apply-templates /> </xsl:element> </xsl:template> <!-- identity template --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>
- A customized Java extension example
You can apply it to any well-formed XML file. The date string format can be provided by <xsl:param> if desired. <h5>XSLT sourece </h5><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xobj="com.example.XObj" version ="1.0"> <!--<xsl:variable name="contextObj" select="xobj:new(.)" />--> <xsl:template match = "@*|node()"> <xsl:copy> <xsl:apply-templates select = "@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="/*"> <xsl:element name="{name(.)}" > <xsl:element name = "today-date"> <xsl:value-of select="xobj:getDateString('EEE, MMM d, yyyy')" /> </xsl:element> <xsl:apply-templates /> </xsl:element> </xsl:template> </xsl:stylesheet>
<h5>Java Code</h5>package com.example; import java.util.Date; import java.text.SimpleDateFormat; public class XObj { public static String getDateString(String format) { SimpleDateFormat df = new SimpleDateFormat(format); return df.format(new Date()); } }
