XML technologies / XSLT / XSLT Cookbook / Extending and embedding XSLT / Adding extension elements with Java.
(Excerpt from “XSLT Kochbuch” by Sal Mangano)
Problem
Extend XSLT by adding elements with custom behavior.
Solution
Earlier sections used vendor extensions. Here you build extension elements from scratch. Unlike extension functions, these require detailed knowledge of a processor’s implementation. Processor designs differ widely, so much of the code will not be portable.
Start with syntactic convenience rather than new functionality. XSLT often needs a context change to another node. One idiom is xsl:for-each. The confusing point is that the goal is not iteration, but switching to the single node selected in xsl:for-each by select:
<xsl:for-each select="document('new.xml')">
<!-- Bearbeite neues Dokument -->
</xsl:for-each>Implement an extension named xslx:set-context behaving like xsl:for-each but processing only the first node in the set defined by select, usually a one-node set anyway.
Saxon requires interface com.icl.saxon.style.ExtensionElementFactory to implement all extension elements for a given namespace. The factory creates them from their local names. A second extension, templtext, follows later.
package com.ora.xsltckbk;
import com.icl.saxon.style.ExtensionElementFactory;
import org.xml.sax.SAXException;
public class CkBkElementFactory implements ExtensionElementFactory {
public Class getExtensionClass(String localname) {
if (localname.equals("set-context")) return CkBkSetContext.class;
if (localname.equals("templtext")) return CkBkTemplText.class;
return null;
}
}A stylesheet extension requires a namespace ending in / followed by the factory’s fully qualified name. Its prefix must also appear in attribute extension-element-prefixes on xsl:stylesheet:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xslx="http://com.ora.xsltckbk.CkBkElementFactory" extension-element-prefixes="xslx">
<xsl:template match="/">
<xslx:set-context select="foo/bar">
<xsl:value-of select="."/>
</xslx:set-context>
</xsl:template>
</xsl:stylesheet>The implementation of set-context extends com.icl.saxon.style.StyleElement and must implement methods prepareAttributes( ) and process( ), usually along with the other methods in this table.
Table: Important Saxon StyleElement methods.
Method | Effect |
| Extensions always return |
| Returns |
| Called at compile time to parse extension attributes and perform local validation. |
| Called after all stylesheet elements have validated locally, allowing cross-validation with parents and children. |
| Called at runtime to execute the extension. It may inspect and change context information but must not change the stylesheet tree. |
The xslx:set-context element was easy: its code was borrowed from Saxon’s XSLForEach implementation and changed to do what XSLForEach does, but only once:
public class CkBkSetContext extends com.icl.saxon.style.StyleElement {
Expression select = null;
public boolean isInstruction( ) {
return true;
}
public boolean mayContainTemplateBody( ) {
return true;
}Ensure attribute @select exists, then call makeExpression to parse it into an XPath expression:
public void prepareAttributes( )
throws TransformerConfigurationException {
StandardNames sn = getStandardNames( );
AttributeCollection atts = getAttributeList( );
String selectAtt = null;
for (int a=0; a<atts.getLength( ); a++) {
int nc = atts.getNameCode(a);
int f = nc & 0xfffff;
if (f == sn.SELECT) {
selectAtt = atts.getValue(a);
} else {
checkUnknownAttribute(nc);
}
}
if (selectAtt= =null) {
reportAbsence("select");
} else {
select = makeExpression(selectAtt);
}
}
public void validate( ) throws TransformerConfigurationException {
checkWithinTemplate( );
}This matches Saxon’s for-each except that, instead of iterating over selection.hasMoreElements, it checks once, extracts the element, sets context and current node, processes children, then restores the context.
public void process(Context context) throws TransformerException
{
NodeEnumeration selection = select.enumerate(context, false);
if (!(selection instanceof LastPositionFinder)) {
selection = new LookaheadEnumerator(selection);
}
Context c = context.newContext( );
c.setLastPositionFinder((LastPositionFinder)selection);
int position = 1;
if (selection.hasMoreElements( )) {
NodeInfo node = selection.nextElement( );
c.setPosition(position++);
c.setCurrentNode(node);
c.setContextNode(node);
processChildren(c);
context.setReturnValue(c.getReturnValue( ));
}
}
}The next extension adds genuine functionality rather than another implementation of an existing feature.
An entire chapter on code generation shows my interest. XSLT excels at XML manipulation but its verbose output syntax can be awkward. Consider this native XSLT task generating C++:
<classes>
<class>
<name>MyClass1</name>
</class>
<class>
<name>MyClass2</name>
</class>
<class>
<name>MyClass3</name>
<bases>
<base>MyClass1</base>
<base>MyClass2</base>
</bases>
</class>
</classes>A stylesheet converting this XML to C++ might be:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="class">
class <xsl:value-of select="name"/> <xsl:apply-templates select="bases"/>
{
public:
<xsl:value-of select="name"/>( ) ;
~<xsl:value-of select="name"/>( ) ;
<xsl:value-of select="name"/>(const <xsl:value-of select="name"/>& other) ;
<xsl:value-of select="name"/>& operator =(const <xsl:value-of select="name"/>
& other) ;
} ;
</xsl:template>
<xsl:template match="bases">
<xsl:text>: public </xsl:text>
<xsl:for-each select="base">
<xsl:value-of select="."/>
<xsl:if test="position( ) != last( )">
<xsl:text>, public </xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>
<xsl:template match="text( )"/>
</xsl:stylesheet>This is tedious to write and hard to read: C++ is buried in markup.
Extension xslx:templtext addresses this with an alternative to xsl:text allowing special escape sequences. Each is delimited by backslashes (\) and has two forms. Braces { and } would resemble AVTs and XQuery, but code generators use them frequently, so I chose backslashes.
Escape sequence | Equivalent XSLT |
|
|
|
|
a XSLT 2.0 offers this through <xsl:value-of select="ausdruck" separator="trennzeichen" />.
The generator now becomes:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xslx="http://com.ora.xsltckbk.CkBkElementFactory" extension-element-prefixes="xslx">
<xsl:output method="text"/>
<xsl:template match="class">
<xslx:templtext>
class \name\ <xsl:apply-templates select="bases"/>
{
public:
\name\( ) ;
~\name\( ) ;
\name\(const \name\& other) ;
\name\& operator =(const \name\& other) ;
} ;
</xslx:templtext>
</xsl:template>
<xsl:template match="bases">
<xslx:templtext>: public \base%', public '\</xslx:templtext>
</xsl:template>
<xsl:template match="text( )"/>
</xsl:stylesheet>This is easier to read and write, and useful for generating much boilerplate text. Purists may object that foreign syntax is harder to manipulate as XML. That is valid, but many developers would otherwise reject XSLT in favor of Perl because its syntax is more concise. Enough hesitation: here is the code.
package com.ora.xsltckbk;
import java.util.Vector ;
import java.util.Enumeration ;
import com.icl.saxon.tree.AttributeCollection;
import com.icl.saxon.*;
import com.icl.saxon.expr.*;
import javax.xml.transform.*;
import com.icl.saxon.output.*;
import com.icl.saxon.trace.TraceListener;
import com.icl.saxon.om.NodeInfo;
import com.icl.saxon.om.NodeEnumeration;
import com.icl.saxon.style.StyleElement;
import com.icl.saxon.style.StandardNames;
import com.icl.saxon.tree.AttributeCollection;
import com.icl.saxon.tree.NodeImpl;First declare constants for the simple finite-state machine parsing escape sequences:
public class CkBkTemplText extends com.icl.saxon.style.StyleElement
{
private static final int SCANNING_STATE = 0 ;
private static final int FOUND1_STATE = 1 ;
private static final int EXPR_STATE = 2 ;
private static final int FOUND2_STATE = 3 ;
private static final int DELIMIT_STATE = 4 ;
...Private classes implement the mini-language inside xslx:templtext. Base class CkBkTemplParam stores literal text preceding an escape sequence:
private class CkBkTemplParam
{
public CkBkTemplParam(String prefix)
{
m_prefix = prefix ;
}
public void process(Context context) throws TransformerException
{
if (!m_prefix.equals(""))
{
Outputter out = context.getOutputter( );
out.setEscaping(false);
out.writeContent(m_prefix);
out.setEscaping(true);
}
}
protected String m_prefix ;
}Class CkBkValueTemplParam extends CkBkTemplParam and implements a simple Value-of-Escape sequence \ausdr\. To simplify this example, disabled output escaping is the default inside xslx:templtext elements:
private class CkBkValueTemplParam extends CkBkTemplParam
{
public CkBkValueTemplParam(String prefix, Expression value)
{
super(prefix) ;
m_value = value ;
}
public void process(Context context) throws TransformerException
{
super.process(context) ;
Outputter out = context.getOutputter( );
out.setEscaping(false);
if (m_value != null)
{
m_value.outputStringValue(out, context);
}
out.setEscaping(true);
}
private Expression m_value ;
}Class CkBkTemplParam implements \ausdr%trennzeichen\, largely imitating Saxon class XslForEach:
private class CkBkListTemplParam extends CkBkTemplParam
{
public CkBkListTemplParam(String prefix, Expression list, Expression delimit)
{
super(prefix) ;
m_list = list ;
m_delimit = delimit ;
}
public void process(Context context) throws TransformerException
{
super.process(context) ;
if (m_list != null)
{
NodeEnumeration m_listEnum = m_list.enumerate(context, false);
Outputter out = context.getOutputter( );
out.setEscaping(false);
while(m_listEnum.hasMoreElements( ))
{
NodeInfo node = m_listEnum.nextElement( );
if (node != null)
{
node.copyStringValue(out);
}
if (m_listEnum.hasMoreElements( ) && m_delimit != null)
{
m_delimit.outputStringValue(out, context);
}
}
out.setEscaping(true);
}
}
private Expression m_list = null;
private Expression m_delimit = null ;
}The last private class, CkBkStyleTemplParam, stores elements nested inside xslx:templtext, such as xsl:apply-templates:
private class CkBkStyleTemplParam extends CkBkTemplParam
{
public CkBkStyleTemplParam(StyleElement snode)
{
m_snode = snode ;
}
public void process(Context context) throws TransformerException
{
if (m_snode.validationError != null)
{
fallbackProcessing(m_snode, context);
}
else
{
try
{
context.setStaticContext(m_snode.staticContext);
m_snode.process(context);
}
catch (TransformerException err)
{
throw snode.styleError(err);
}
}
}
}The next three methods are standard. To make standard attribute disable-output-escaping affect escape output, save its value in prepareAttributes( ). Saxon source file XslText.java has the required code:
public boolean isInstruction( )
{
return true;
}
public boolean mayContainTemplateBody( )
{
return true;
}
public void prepareAttributes( ) throws TransformerConfigurationException
{
StandardNames sn = getStandardNames( );
AttributeCollection atts = getAttributeList( );
for (int a=0; a<atts.getLength( ); a++)
{
int nc = atts.getNameCode(a);
checkUnknownAttribute(nc);
}
}Validation is an opportunity to parse xslx:templtext content for escape sequences. Send text nodes to a parser function and convert element content into CkBkStyleTemplParam instances. Member variable m_TemplParms is a vector storing parse results:
public void validate( ) throws TransformerConfigurationException
{
checkWithinTemplate( );
m_TemplParms = new Vector( ) ;
NodeImpl node = (NodeImpl)getFirstChild( );
String value ;
while (node!=null)
{
if (node.getNodeType( ) = = NodeInfo.TEXT)
{
parseTemplText(node.getStringValue( )) ;
}
else
if (node instanceof StyleElement)
{
StyleElement snode = (StyleElement) node;
m_TemplParms.addElement(new CkBkStyleTemplParam(snode)) ;
}
node = (NodeImpl)node.getNextSibling( );
}
}Method process iterates over m_TemplParms and invokes each implementation’s process method:
public void process(Context context) throws TransformerException
{
Enumeration iter = m_TemplParms.elements( ) ;
while (iter.hasMoreElements( ))
{
CkBkTemplParam param = (CkBkTemplParam) iter.nextElement( ) ;
param.process(context) ;
}
}These private functions implement a simple state-machine parser, easier with a regular-expression engine available in Java 1.4.1. Two consecutive backslashes (\\) become one literal backslash. Likewise, %% becomes a single %:
private void parseTemplText(String value)
{
// Dieser endliche Automat parst den Text und sucht nach Parametern
int ii = 0 ;
int len = value.length( ) ;
int state = SCANNING_STATE ;
StringBuffer temp = new StringBuffer("") ;
StringBuffer expr = new StringBuffer("") ;
while(ii < len)
{
char c = value.charAt(ii++) ;
switch (state)
{
case SCANNING_STATE:
{
if (c == '\\')
{
state = FOUND1_STATE ;
}
else
{
temp.append(c) ;
}
}
break ;
case FOUND1_STATE:
{
if (c == '\\')
{
temp.append(c) ;
state = SCANNING_STATE ;
}
else
{
expr.append(c) ;
state = EXPR_STATE ;
}
}
break ;
case EXPR_STATE:
{
if (c == '\\')
{
state = FOUND2_STATE ;
}
else
{
expr.append(c) ;
}
}
break ;
case FOUND2_STATE:
{
if (c = = '\\')
{
state = EXPR_STATE ;
expr.append(c) ;
}
else
{
processParam(temp, expr) ;
state = SCANNING_STATE ;
temp = new StringBuffer("") ; temp.append(c) ;
expr = new StringBuffer("") ;
}
}
break ;
}
}
if (state == FOUND1_STATE || state == EXPR_STATE)
{
compileError("xslx:templtext dangling \\");
}
else
if (state == FOUND2_STATE)
{
processParam(temp, expr) ;
}
else
{
processParam(temp, new StringBuffer("")) ;
}
}
private void processParam(StringBuffer prefix, StringBuffer expr)
{
if (expr.length( ) == 0)
{
m_TemplParms.addElement(new CkBkTemplParam(new String(prefix))) ;
}
else
{
processParamExpr(prefix, expr) ;
}
}
private void processParamExpr(StringBuffer prefix, StringBuffer expr)
{
int ii = 0 ;
int len = expr.length( ) ;
int state = SCANNING_STATE ;
StringBuffer list = new StringBuffer("") ;
StringBuffer delimit = new StringBuffer("") ;
while(ii < len)
{
char c = expr.charAt(ii++) ;
switch (state)
{
case SCANNING_STATE:
{
if (c == '%')
{
state = FOUND1_STATE ;
}
else
{
list.append(c) ;
}
}
break ;
case FOUND1_STATE:
{
if (c == '%')
{
list.append(c) ;
state = SCANNING_STATE ;
}
else
{
delimit.append(c) ;
state = DELIMIT_STATE ;
}
}
break ;
case DELIMIT_STATE:
{
if (c == '%')
{
state = FOUND2_STATE ;
}
else
{
delimit.append(c) ;
}
}
break ;
}
}
try
{
if (state = = FOUND1_STATE)
{
compileError("xslx:templtext trailing %");
}
else
if (state == FOUND2_STATE)
{
compileError("xslx:templtext extra %");
}
else
if (state = = SCANNING_STATE)
{
String prefixStr = new String(prefix) ;
Expression value = makeExpression(new String(list)) ;
m_TemplParms.addElement(new CkBkValueTemplParam(prefixStr, value)) ;
}
else
{
String prefixStr = new String(prefix) ;
Expression listExpr = makeExpression(new String(list)) ;
Expression delimitExpr = makeExpression(new String(delimit)) ;
m_TemplParms.addElement(new CkBkListTemplParam(prefixStr, listExpr, delimitExpr)) ;
}
}
catch(Exception e)
{
}
}
// Ein Vektor von CBkTemplParms parse form text
private Vector m_TemplParms = null;
}Extend xslx:templtext with useful improvements, such as multiple lists in a list escape sequence, for example /expr1%delim1%expr2%delim2/. Its XSLT equivalent might be:
<xsl:for-each select="expr1">
<xsl:variable name="pos" select="position( )"/>
<xsl:value-of select="."/>
<xsl:if test="$pos != last( )">
<xsl:value-of select="delim1"/>
</xsl:if>
<xsl:value-of select="expr2[$pos]"/>
<xsl:if test="$pos != last( )">
<xsl:value-of select="delim2"/>
</xsl:if>
</xsl:for-each >This helps expand paired lists, such as C++ parameters containing name/type pairs. The XSLT only roughly specifies semantics: it assumes node sets expr1 and expr2 have equal sizes. A real implementation should keep expanding while either list has nodes, suppressing separators for exhausted lists. Better still, control this through attributes on xslx:templtext.
Discussion
Space prevents a full implementation of these elements for Xalan, but the introduction should make the approach clear.
Copyright © 2006 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “XSLT Kochbuch” is subject to the same conditions as the bound edition. The work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O'Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de