Prevent spurious namespace output from Java (xalan) XSLT
November 04, 2010 20:24:32 Last update: November 04, 2010 20:24:55
XSLT by default writes namespace declarations in the output. Most of the time it's spurious, sometimes outright wrong.
- Take this XML:
<?xml version="1.0" encoding="ISO-8859-1"?> <event> <title>A test event</title> <details> <timestamp>1288651500854</timestamp> <description>Something happened</description> </details> </event>
- And this XSL:
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:java="http://xml.apache.org/xslt/java"> <xsl:output method="html"/> <xsl:template match="/"> <xsl:apply-templates select="event/details"> <xsl:with-param name="title" select="title"/> </xsl:apply-templates> </xsl:template> <xsl:template match="details"> <xsl:param name="title"/> Title: <xsl:value-of select="$title"/><br/> Timestamp: <xsl:value-of select="java:DateUtil.getDate(number(timestamp))"/><br/> Description: <xsl:value-of select="description"/><br/> </xsl:template> </xsl:stylesheet>
whereDateUtil.javais:import java.util.Date; public class DateUtil { public static Date getDate(long time) { return new Date(time); } }
- The output is (with JDK1.6):
Title: <br xmlns:java="http://xml.apache.org/xslt/java"> Timestamp: Mon Nov 01 17:45:00 CDT 2010<br> Description: Something happened<br>
The namespace declaration went to the<br>element, not the timestamp where it belongs. - To remove the namespace info, add
exclude-result-prefixesto the XSL:<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:java="http://xml.apache.org/xslt/java" exclude-result-prefixes="java"> <!-- this removes namespace info --> <xsl:output method="html"/> <xsl:template match="/"> <xsl:apply-templates select="event/details"> <xsl:with-param name="title" select="title"/> </xsl:apply-templates> </xsl:template> <xsl:template match="details"> <xsl:param name="title"/> Title: <xsl:value-of select="$title"/><br/> Timestamp: <xsl:value-of select="java:DateUtil.getDate(number(timestamp))"/><br/> Description: <xsl:value-of select="description"/><br/> </xsl:template> </xsl:stylesheet>