2010-04-14 - Jakarta Taglibs has been retired.

For more information, please explore the Attic.

Jakarta Project: XTags library: Tags for working with XML, XPath and XSLT

Version: 1.0

Table of Contents

Overview

XTags is a JSP tag library for working with XSLT and XPath. XTags lets you navigate, process and style XML documents directly in JSP.

XTags makes heavy use of the XPath expression language. For a good tutorial on XPath you could try the either the Zvon tutorial or the specification.

XTags is currently built on top of dom4j the flexible open source XML framework for the Java platform. Though increasingly XTags will use a pluggable XPath engine to support the travesal of DOM and Java Beans too.

To begin with you need to parse an XML document from somewhere. You can parse a variety of sources of XML documents from local resources, the output of JSP or external web services.

You can parse the body of the tag

    <xtags:parse>
        <root>
            <child/>
        </root>
    </xtags:parse>

Or parse an absolute URL via the "url" attribute

    <xtags:parse url="http://something.com"/>

You can parse a web app resource using an absolute URI relative to the web-app context using the "uri" attribute

    <xtags:parse uri="/data/foo.xml"/>

Or you can use a URI relative to the the current JSP file

    <xtags:parse uri="foo.xml"/>

Then for more complex requirements such as parsing the output of a piece of JSP, you can do the following (provided you are using a JSP 1.2 container)

    <xtags:parse>
        <jsp:include page="foo.jsp"/>
    </xtags:parse>

Until then you can use the IO tag library to make these requests such as

    <xtags:parse>
        <io:request url="/foo.jsp"/>
    </xtags:parse>

Though the above would result in a seperate HTTP request which would loose all page, request and session scope state. So if it must be in the same request the following should work though care should be taken to avoid scripting variable clashes

    <xtags:parse>
        <%@ include file="/foo.jsp" %>
    </xtags:parse>

To parse the output of an XML-RPC (or SOAP) call, using the IO taglib you could do the following.

    <xtags:parse>
        <io:xmlrpc url="/xmlrpc_echo.jsp">
         <io:pipe>
          <methodCall>
             <methodName>examples.getStateName</methodName>
             <params>
                <param>
                   <value><i4>41</i4></value>
                   </param>
                </params>
             </methodCall>
         </io:pipe>
        </io:xmlrpc>

    </xtags:parse>

Once you have a document parsed you can navigate around its structure using XPath expressions in a similar manner to that used in XSLT.

Loops are as follows (an optional variable id can be specified to define a scriptlet expression inside the loop):-

  <xtags:forEach select="expression">
    ...
  </xtags:forEach>

Simple conditional branching is:-

  <xtags:if test="booeanExpression">
    ...
  </xtags:if>

More complex conditional branching is:-

  <xtags:choose>
    <xtags:when test="booeanExpression">
      ...
    </xtags:when>
    <xtags:when test="booeanExpression2">
      ...
    </xtags:when>
    <xtags:otherwise>
      ...
    </xtags:otherwise>
  </xtags:choose>

Expression evaluation

  <xtags:valueOf select="expression"/>

Defining scriptlet variables

  <xtags:variable id="variableName" select="expression"/>

All these tags are very similar to their XSLT equivalents, so anyone who's done XSLT before should find them familiar. There's also an <xtags:style> tag which performs complete XSL transform in one tag.

Accessing JSP scopes from XPath

XPath expressions can use variables with the syntax $foo. XTags binds these variables to either page/request/session/application scope attributes or request parameters which allows xtags to be used as a conditional logic scripting language too - even without the existence of XML documents.

A prefix can be used to denote the exact JSP scope from which a variable comes from such as $request:foo to denote request scope. There now follows a full breakdown of all the current JSP scopes

$foo maps to pageContext.findAttribute("foo")
$page:foo maps to page scope
$request:foo maps to request scope
$session:foo maps to session scope
$app:foo maps to application scope
$param:foo maps to request.getParameter("foo")
$initParam:foo maps to request.getInitParameter("foo")
$cookie:foo maps to the cookie's value for name foo
$header:foo maps to request.getHeader("foo")

For example, the following JSP would branch logically based on the value of the (say) request parameter "param":-

  <xtags:choose>
    <xtags:when test="$param='a'">
      current param is 'a'
    </xtags:when>
    <xtags:when test="$param='b'">
      current param is 'b'
    </xtags:when>
    <xtags:otherwise>
      no valid param selected
    </xtags:otherwise>
  </xtags:choose>

XTags even supports the <xtags:stylesheet> <xtags:template> and <xtags:applyTemplates> tags from XSLT too though the body of a template must be an Action object or a seperate JSP file.

Requirements

This custom tag library depends on a servlet container that supports the JavaServer Pages Specification, version 1.1 or higher and also requires a distribution of dom4j version 1.1 or later. To be able to use the <xtags:style> tag then a distribution of JAXP is required along with an XSLT implementation such as xalan.jar and crimson.jar. We recommend using this tag library with a Servlet 2.3 and JSP 1.2 container such as Tomcat 4.0 or WebLogic 6.1.

Configuration

Follow these steps to configure your web application with this tag library:

To use the tags from this library in your JSP pages, add the following directive at the top of each page:

<%@ taglib uri="http://jakarta.apache.org/taglibs/xtags-1.0" prefix="xtags" %>

where "xtags" is the tag name prefix you wish to use for tags from this library. You can change this value to any prefix you like.

Tag Summary

XSLT Tags
stylePerforms an XSL transformation on the given XML document.
param Passes in parameters to the XSLT transformation
 
XPath Tags
parse Parsers some XML either from a given relative URI, an explicit URL or from the body of this tag. The URL is relative to the current web application or web page.
valueOfEvaluates the given XPath expression on the current context node and outputs the result as text
forEach Evaluates the given XPath expression and iterates over the result, setting the context node to each element in the iteration. If the "id" attribute is specified then a scripting attribute will be defined with the current item of the iteration.
chooseBehaves like the corresponding XSLT tag. A choose tag contains zero or more when tags together with an optional otherwise tag.
whenBehaves like the corresponding XSLT tag
otherwiseBehaves like the corresponding XSLT tag.
breakBehaves like the Java 'break' statement causing the current foreach tag iteration to terminate.
ifBehaves like the corresponding XSLT tag, the body is evaluated if the XPath selection finds one or more nodes
variable Defines a scripting variable with the given id and the the value of the given XPath expression. By default the type will be a String. If the "type" attribute specifies a type of 'node' it convert the result to an org.dom4j.Node otherwise the result will be an Object or List.
stylesheetPerforms a stylesheet on the current context. The body of this tag defines the stylesheet
templateDefines a template rule in an XSLT stylesheet. For each node which matches the pattern the JSP will be called. If no JSP file is specified then the value is copied using an XSLT style copy-of operation.
applyTemplatesPerforms an apply templates like the XSLT tag.
elementLike the XSLT tag, creates a new XML element.
attributeLike the XSLT tag, creates a new attribute for the outer element tag.
outputDefined the output format to use for the tags inside its body
copyGenerates a shallow copy of the current context like the XSLT <xsl:copy/> tag.
copyOfGenerates a deep copy of the current context like the XSLT <xsl:copy-of/> tag.
contextBehaves like a <xtags:forEach> tag but it is guarrenteed to evaluate its body exactly once whether the selection matches anything or not. This tag can be useful for setting the context to some deeply nested path to make tags within its body have a simpler path expressions.
removeRemoves the nodes selected via the XPath expression from the current document.
addParses it's body (as an XML fragment) and appends the contents to the current node. The current node must be an Element.
replaceParses it's body (as an XML fragment) and replaces the contents of the current node with the resulting nodes. The current node must be an Element.
 

Tag Reference

style Availability: 1.0

Performs an XSL transformation on the given XML document.

Tag BodyJSP    
Restrictions

AttributesNameRequired Runtime Expression Evaluation Availability
 document  No   Yes  
 

The XML document instance to use as a source

 xml  No   Yes  
 

The URL or URI of the XML document to style

 xmlReader  No   Yes  
 

The Reader of the XML stream to style

 xmlSource  No   Yes  
 

The JAXP Source of XML to style

 xsl  No   Yes  
 

The URL or URI of the XSLT for the transformation

 xslReader  No   Yes  
 

The Reader of the XSLT stream for the transformation

 xslSource  No   Yes  
 

The JAXP Source of XSLT for the transformation

 result  No   Yes  
 

The JAXP Result to send the output to

 writer  No   Yes  
 

The Writer to send the output to

 outputMethod  No   Yes  
 

The output method of the transformation, either xml, html or text

VariablesNone
 
 


<xtags:style xml="foo.xml" xsl="bar.xsl"/>

<xtags:style document="<%= myDoc %>" xsl="bar.xsl"/>

<xtags:style xsl="bar.xsl"/>
    <!-- this is the XML which will get styled -->
    <root>
        <foo bar="123"/>
    </root>
</xtags:style>
      

param Availability: 

Passes in parameters to the XSLT transformation

Tag BodyJSP    
Restrictions None
AttributesNameRequired Runtime Expression Evaluation Availability
 name  Yes   Yes  
 

The name of the XSLT parameter

 value  No   Yes  
 

The value of the XSLT parameter

VariablesNone
 
 


<xtags:style xml="foo.xml" xsl="bar.xsl">
  <xtags:param name="foo" value="123"/>
  <xtags:param name="bar">456</xtags:param>
</xtags:style>
      

parse Availability: 

Parsers some XML either from a given relative URI, an explicit URL or from the body of this tag. The URL is relative to the current web application or web page.

Tag BodyJSP    
Restrictions

None

AttributesNameRequired Runtime Expression Evaluation Availability
 id  No   No  
 

The identifier to use for the scripting variable created which represents the current XML Document instance.

 uri  No   Yes  
 

The URI to the resource to be used to parse the document. If the URI starts with a '/' character then this will be relative to the current web application directory. If the URI does not start with '/' then it is relative to the current page.

 url  No   Yes  
 

The absolute URL of the resource to parse as XML.

 reader  No   Yes  
 

Allows a Reader of the stream to be parsed as XML to be specified

 validate  No   Yes  
 

Specifies whether validation should be enabled or disabled.

VariablesNone
 
 


<xtags:parse id="doc1">
  <root>
    <author firstName="James" surname="Strachan"/>
  </root>
</xtags:parse>

<xtags:parse id="docByURL" url="http://www.acme.com/foo/bar.xml"/>

<xtags:parse id="docByAbsoluteURI" uri="/foo/bar.xml"/>

<xtags:parse id="docByRelativeURI" uri="bar.xml"/>
      

valueOf Availability: 

Evaluates the given XPath expression on the current context node and outputs the result as text

Tag Bodyempty    
Restrictions

AttributesNameRequired Runtime Expression Evaluation Availability
 select  Yes   Yes  
 

The XPath expression to select on the current context

 context  No   Yes  
 

The context to use on which to evaluate the XPath expression. Could be a Document, a Node or a NodeSet

VariablesNone
 
 


      <xtags:valueOf select="//author/@surname" /> 
      

forEach Availability: 

Evaluates the given XPath expression and iterates over the result, setting the context node to each element in the iteration. If the "id" attribute is specified then a scripting attribute will be defined with the current item of the iteration.

Tag BodyJSP    
Restrictions

AttributesNameRequired Runtime Expression Evaluation Availability
 select  Yes   Yes  
 

The XPath expression to select on the current context

 sort  No   Yes  
 

The optional XPath expression to sort the nodes by

 distinct  No   Yes  
 

If this is set to true and the sort attribute is specified then duplicates are removed.

 ascending  No   Yes  
 

This boolean attribute defaults to true. If set to false then the sort is made in descending order.

 context  No   Yes  
 

The context to use on which to evaluate the XPath expression. Could be a Document, a Node or a NodeSet

 id  No   No  
 

The identifier to use for the scripting variable created which represents the current context (Node)

 type  No   No  
 

The type of the scripting variable to declare. Should be node, string, number or org.dom4j.Node, java.lang.String or java.lang.Number. Defaults to 'string'

VariablesNone
 
 


<xtags:forEach select="//author">
  <xtags:valueOf select="@name"/>      
</xtags:forEach>

<xtags:forEach select="//author/@name" id="name">
  <%= name %>
</xtags:forEach>
       

choose Availability: 

Behaves like the corresponding XSLT tag. A choose tag contains zero or more when tags together with an optional otherwise tag.

Tag BodyJSP    
Restrictions

AttributesNone
VariablesNone
 
 


<xtags:choose>
  <xtags:when test="firstName">
    Hello <xtags:valueOf select="@firstName"/>
  </xtags:when>
  <xtags:otherwise>
    Hello there friend
  </xtags:otherwise>
</xtags:choose>
       

when Availability: 

Behaves like the corresponding XSLT tag

Tag BodyJSP    
Restrictions

Should be used within a <xtags:choose> tag

AttributesNameRequired Runtime Expression Evaluation Availability
 test  Yes   Yes  
 

The XPath predicate expression to test whether the body of this tag should be evaluated

 context  No   Yes  
 

The context to use on which to evaluate the XPath expression. Could be a Document, a Node or a NodeSet

VariablesNone
 
 


      

otherwise Availability: 

Behaves like the corresponding XSLT tag.

Tag BodyJSP    
Restrictions

Should be used within a <xtags:choose> tag

AttributesNone
VariablesNone
 
 


      

break Availability: 

Behaves like the Java 'break' statement causing the current foreach tag iteration to terminate.

Tag Bodyempty    
Restrictions

Should be used within a <xtags:choose> tag

AttributesNone
VariablesNone
 
 


      

if Availability: 

Behaves like the corresponding XSLT tag, the body is evaluated if the XPath selection finds one or more nodes

Tag BodyJSP    
Restrictions

AttributesNameRequired Runtime Expression Evaluation Availability
 test  Yes   Yes  
 

The XPath predicate expression to test whether the body of this tag should be evaluated

 context  No   Yes  
 

The context to use on which to evaluate the XPath expression. Could be a Document, a Node or a NodeSet

VariablesNone
 
 


<xtags:if select="@location='UK'">
  UK based
</xtags:if>
      

variable Availability: 

Defines a scripting variable with the given id and the the value of the given XPath expression. By default the type will be a String. If the "type" attribute specifies a type of 'node' it convert the result to an org.dom4j.Node otherwise the result will be an Object or List.

Tag Bodyempty    
Restrictions

AttributesNameRequired Runtime Expression Evaluation Availability
 id  Yes   No  
 

The identifier to use for the scripting variable created which represents the value of the XPath expression

 type  No   No  
 

The type of the scripting variable to declare. Can use the aliases of node, string, number, list, object. Or the full Java class names of org.dom4j.Node, java.lang.String, java.lang.Number, java.util.List or java.lang.Object. This value defaults to 'string'

 select  Yes   Yes  
 

The XPath expression to select on the current context

 context  No   Yes  
 

The context to use on which to evaluate the XPath expression. Could be a Document, a Node or a NodeSet

VariablesNone
 
 


      <xtags:variable id="surname" select="@surname"/> 
      

stylesheet Availability: 

Performs a stylesheet on the current context. The body of this tag defines the stylesheet

Tag BodyJSP    
Restrictions

AttributesNameRequired Runtime Expression Evaluation Availability
 context  No   Yes  
 

The context to use on which to evaluate the XPath expression. Could be a Document, a Node or a NodeSet

VariablesNone
 
 


<xtags:stylesheet>
  <xtags:template match="author">
    Written by: <xtags:valueOf select="@name"/>
  </xtags:template>

  <xtags:template match="painter">
    <p><xtags:applyTemplates/></p>
  </xtags:template>

  <xtags:template match="books">
    <ul><xtags:applyTemplates select="title"/></ul>
  </xtags:template>
</xtags:stylesheet>
      

template Availability: 

Defines a template rule in an XSLT stylesheet. For each node which matches the pattern the JSP will be called. If no JSP file is specified then the value is copied using an XSLT style copy-of operation.

Tag BodyJSP    
Restrictions None
AttributesNameRequired Runtime Expression Evaluation Availability
 match  Yes   Yes  
 

The XSLT pattern to match for this template

 mode  No   Yes  
 

The XSLT mode of the template. XSLT allows different named modes to be used on the same XSLT pattern. The mode can be specified by <xtags:applyTemplates>

 avt  No   Yes  
 

If set to true (default is false) attribute value templates (strings between curly braces) will be evaluated as XPath expressions, and the value substituted in the output.

 action  No   Yes  
 

The org.dom4j.rule.Action object to run if this template is matched

VariablesNone
 
 


<xtags:stylesheet>
  <xtags:template match="link" avt="true">
    <a href="{@destination}"><xtags:applyTemplates/></a>
  </xtags:template>
</xtags:stylesheet>
      

applyTemplates Availability: 

Performs an apply templates like the XSLT tag.

Tag BodyJSP    
Restrictions

AttributesNameRequired Runtime Expression Evaluation Availability
 select  No   Yes  
 

The XPath expression to select on the current context

 mode  No   Yes  
 

The XSLT mode to match templates to apply

VariablesNone
 
 


      
<xtags:applyTemplates select="foo" />
<xtags:applyTemplates select="bar" mode="summary" />
 
      

element Availability: 

Like the XSLT tag, creates a new XML element.

Tag BodyJSP    
Restrictions

AttributesNameRequired Runtime Expression Evaluation Availability
 name  Yes   Yes  
 

The name of the new element to output

VariablesNone
 
 


      <xtags:element name="author"/> 
      

attribute Availability: 

Like the XSLT tag, creates a new attribute for the outer element tag.

Tag BodyJSP    
Restrictions

Only usable inside an <xtags:element> tag

AttributesNameRequired Runtime Expression Evaluation Availability
 name  Yes   Yes  
 

The name of the new attribute to output

VariablesNone
 
 


      <xtags:attribute name="location">UK</xtags:attribute> 
      

output Availability: 

Defined the output format to use for the tags inside its body

Tag BodyJSP    
Restrictions

AttributesNameRequired Runtime Expression Evaluation Availability
 method  No   Yes  
 

The method of output of the <xtags:copy/> and <xtags:copyOf> tags which is either 'xml' or 'html'

 indent  No   Yes  
 

The indentation string used if pretty printing the output

 omitXmlDeclaration  No   Yes  
 

Whether to omit the XML declaration

VariablesNone
 
 


      
<xtags:output method="xml" indent="yes" omitXmlDeclaration="false">
  <xtags:copyOf select="foo"/>
<xtags:output>

<xtags:output method="html" indent="  ">
  <xtags:copyOf select="html/body"/>
<xtags:output>
 
      

copy Availability: 

Generates a shallow copy of the current context like the XSLT <xsl:copy/> tag.

Tag BodyJSP    
Restrictions

AttributesNameRequired Runtime Expression Evaluation Availability
 select  Yes   Yes  
 

The XPath expression to select on the current context

 context  No   Yes  
 

The context to use on which to evaluate the XPath expression. Could be a Document, a Node or a NodeSet

VariablesNone
 
 


      
<xtags:copy select="foo">
some new text content
</xtags:copy>
 
      

copyOf Availability: 

Generates a deep copy of the current context like the XSLT <xsl:copy-of/> tag.

Tag BodyJSP    
Restrictions

AttributesNameRequired Runtime Expression Evaluation Availability
 select  Yes   Yes  
 

The XPath expression to select on the current context

 context  No   Yes  
 

The context to use on which to evaluate the XPath expression. Could be a Document, a Node or a NodeSet

VariablesNone
 
 


      <xtags:copyOf select="@*|text()" /> 
      

context Availability: 

Behaves like a <xtags:forEach> tag but it is guarrenteed to evaluate its body exactly once whether the selection matches anything or not. This tag can be useful for setting the context to some deeply nested path to make tags within its body have a simpler path expressions.

Tag BodyJSP    
Restrictions

AttributesNameRequired Runtime Expression Evaluation Availability
 select  Yes   Yes  
 

The XPath expression to select on the current context

 context  No   Yes  
 

The context to use on which to evaluate the XPath expression. Could be a Document, a Node or a NodeSet

VariablesNone
 
 


<xtags:context select="a/b/c">
  <xtags:valueOf select="@d"/>
  <xtags:valueOf select="@e"/>
  <xtags:valueOf select="x"/>
</xtags:context>

As an alternative to:-

<xtags:valueOf select="a/b/c/@d"/>
<xtags:valueOf select="a/b/c/@e"/>
<xtags:valueOf select="a/b/c/x"/>
      

remove Availability: 

Removes the nodes selected via the XPath expression from the current document.

Tag Bodyempty    
Restrictions

AttributesNameRequired Runtime Expression Evaluation Availability
 select  Yes   Yes  
 

The XPath expression to select on the current context which all nodes are removed from the current context's document

VariablesNone
 
 


<xtags:remove select="//a[@x='123']"/>
      

add Availability: 

Parses it's body (as an XML fragment) and appends the contents to the current node. The current node must be an Element.

Tag Bodyjsp    
Restrictions

AttributesNameRequired Runtime Expression Evaluation Availability
 before  No   Yes  
 
 after  No   Yes  
 
VariablesNone
ExamplesNone
replace Availability: 

Parses it's body (as an XML fragment) and replaces the contents of the current node with the resulting nodes. The current node must be an Element.

Tag Bodyjsp    
Restrictions

AttributesNone
VariablesNone
ExamplesNone

Examples

See the example application xtags-examples.war for examples of the usage of the tags from this custom tag library.

Java Docs

Java programmers can view the java class documentation for this tag library as javadocs.

Revision History

Review the complete revision history of this tag library.