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.
<products>
<product>
This is a complex node
</product>
<product>
This is a complex node
</product>
</products>
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"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:nxp="http://www.nxp.com">
<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:function>
<xsl:template match="product">
<product processedTimestamp="{nxp:getTimestamp()}">
<xsl:apply-templates/>
</product>
</xsl:template>
</xsl:stylesheet>
So when you execute that stylesheet you will end up with product tags having a new attribute like below:
<product processedTimestamp="1350635976117"> ... </product>
No comments:
Post a Comment