How to write xslt extended method? Can you give an example?

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" 
      <!-- add a today-date to your XML under the root -->
      <xsl:template match="/*">
        <xsl:element name="{name(.)}">
            <xsl:value-of select="java:util.Date.new()" />
          <xsl:apply-templates />
      <!-- identity template -->
      <xsl:template match="@*|node()">
            <xsl:apply-templates select="@*|node()"/>
  • 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" 
      version ="1.0">
      <!--<xsl:variable name="contextObj" select="xobj:new(.)" />-->
      <xsl:template match = "@*|node()">
          <xsl:apply-templates select = "@*|node()"/>
      <xsl:template match="/*">
        <xsl:element name="{name(.)}" >
          <xsl:element name = "today-date">
            <xsl:value-of select="xobj:getDateString('EEE, MMM d, yyyy')" /> 
          <xsl:apply-templates />
    <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());
The code can also be found at XSLT Extension, advanced topics


0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.