If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Friday, October 19, 2012

Creating UNIX timestamp with XSLT2.0 (Saxon)

Creating timestamps is a quite often used requirement. If you start googling for how to create one in XSLT, you find exotic solutions. Today I set out to find an elegant one using XSLT extension functions.
If you take a look at the Java API, and in particular java.util.Date, you will see a method getTime() which returns exactly what I need.
long getTime()
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

Now let's see at a simple input XML containing products. For each product we want to generate a timestamp while processing each product node.
    This is a complex node
    This is a complex node

To understand how extension functions with Saxon can be used, take a look here. In this case we really need to construct new Date objects and invoke the method getTime on them. We bind the prefix date to the namespace java:java.util.Date. Next we can construct a new date object with date:new(). To invoke a method on any object you actually have to pass the context object to that method. So date:getTime(date:new()) is actually the java equivalent for new java.util.Date().getTime()
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

  <xsl:function name="nxp:getTimestamp">
    <xsl:value-of select="date:getTime(date:new())"  xmlns:date="java:java.util.Date"/>

  <xsl:template match="product">
   <product processedTimestamp="{nxp:getTimestamp()}">


So when you execute that stylesheet you will end up with product tags having a new attribute like below:
<product processedTimestamp="1350635976117">

No comments:

Post a Comment