JSTL XML Tag LibraryS2C Home « JSTL XML Tag Library

In our second lesson on JSTL tag libraries we look at the XML tag library. The XML tag library consists of ten actions which we can group into three categories, XML core actions, XML flow control actions and XML transform actions. We will look at each of these groups and the actions within each, in much more detail, as we work through this lesson.

Each XML action can have mandatory attributes that have to be populated and each attribute may also allow a run-time expression to be used. If a run-time expression is allowed for an attribute this can be populated using a static string or more interestingly a dynamic value which can be an EL or Java expression or a value set using the <jsp:attribute> standard action. If no run-time expression is allowed for an attribute then you can only populate that attribute using a static string.

The XML tag library in JSTL is based on XPath which provides a concise notation for specifying and then selecting parts of an XML document. XPath can be thought of as a expression language that is used locally for XML actions and to ensure that XPath integrates with the JSTL environment a number of integration rules are administered by the container.

All JSTL XML actions use the select attribute to specify XPath expressions. The select attribute is always specified as a string literal for evaluation by the XPath engine. This helps avoid confusion between XPath expression language that is local to the XML actions and the JSTL expression language that is global to all actions and uses dynamic attributes in the EL version of the tag library.

  • XPath Context for evaluating an expression consists of:
    1. A node or nodeset
    2. Variable bindings
    3. Function library which is limited in JSTL to the core function library of the XPath specification
    4. Namespace prefix definitions which allow namespace prefixes to be used within an XPath expression

XPath Variable BindingsTop

The following table shows the scopes available within an XPath expression to access web application data, which are mapped in the same way as their EL Implicit Objects counterparts:

Expression Mapping
$foopageContext.findAttribute( "foo")
$param:foo request.getParameter( "foo")
$header:foorequest.getHeader( "foo")
$cookie:fooMaps to cookie values for foo
$initParam:fooapplication.getInitParameter( "foo")
$pageScope:foopageContext.getAttribute( "foo", PageContext.PAGE_SCOPE)
$requestScope:foopageContext.getAttribute( "foo", PageContext.REQUEST_SCOPE)
$sessionScope:foopageContext.getAttribute( "foo", PageContext.SESSION_SCOPE)
$applicationScope:foopageContext.getAttribute( "foo", PageContext.APPLICATION_SCOPE)

Java to XPath Type MappingsTop

An XPath variable must reference a java.lang.Object instance in any of the supported scopes, as identified by their namespace prefix. The following table shows the mappings that must be supported:

Java Type XPath Type
java.lang.Booleanboolean
java.lang.Numbernumber
java.lang.Stringstring
Object exported by <x:parse>node-set

XPath to Java Type MappingsTop

Evaluation of XPath expressions evaluate to XPath types. The following table shows their mappings to Java objects:

XPath Type Java Type
boolean - true or falsejava.lang.Boolean
number - Floating-point numberjava.lang.Number
string - Sequence of Universal Character Set (UCS) cahractersjava.lang.String
node-set - Unordered collection of nodes without duplicatesType usable by JSTL XML-manipulation tags in the same JSTL implementation.

Core XML ActionsTop

There are three Core XML actions, these being <x:set> which allows us to set an attribute within any scope, <x:out> which evaluates an XPath expression and outputs the result of the evaluation to the current JspWriter object and <x:parse> which allows us to parse an XML document.

Action /
Attrib. Name
Mandatory Run-time Expression? Default Value Object Type Description
<x:set>
selectYesNoNoneStringXPath expression to be evaluated.
varNoNoNoneStringName of exported scoped variable to hold expression value.
The type of scoped variable is whatever type the select expression evaluates to.
scopeNoNoNoneStringScope that the created scoped variable var exists in.
<x:out>
selectYesNoNoneStringXPath expression to be evaluated.
escapeXmlNoYestrueBooleanIndicates whether the characters < > & ' and " are escaped to their HTML entity codes
<x:parse>
docNoYesNoneString, ReaderThe source XML document to be parsed.
varNoNoNoneStringName of exported scoped variable to hold expression value.
The type of scoped variable is whatever type the select expression evaluates to.
scopeNoNoNoneStringScope that the created scoped variable var exists in.
varDomNoNoNoneStringName of exported scoped variable to hold expression value.
The type of scoped variable is org.w3c.dom.Document.
scopeDomNoNoNoneStringScope that the created scoped variable varDom exists in.
systemIdNoYesNoneStringThe system identifier (URI) used for parsing the XML document.
filterNoYesNoneorg.xml.sax.XMLFilterA filter to be applied to the source document.

<x:set>Top

The <x:set> tag evaluates an XPath expression and stores the result into a scoped variable.

The following code snippets shows the syntax of the <x:set> tag available where the square brackets indicate optional attributes and the curly bracers indicate a choice of options within them where the default is underlined.


// Evaluate XPath expression and save test condition result to var
<x:set select="XPathExpression" var="varName" [scope="{page|request|session|application}"]>

<x:out>Top

The <x:set> tag evaluates an XPath expression and outputs the result of the evaluation to the current JspWriter object.

The following code snippets shows the syntax of the <x:set> tag available where the square brackets indicate optional attributes and the curly bracers indicate a choice of options where the default is underlined.


// Output the result of the XPath evaluation to the current JspWriter object
<x:set select="XPathExpression" [escapeXml="{true|false}"]>

<x:parse>Top

The <x:parse> tag allows us to parse an XML document

The following code snippets shows the two variants of the <x:parse> tag where the square brackets indicate optional attributes and the curly bracers indicate a choice of options where the default is underlined.


// XML document specified via a String or Reader object
<x:parse doc="XMLDocument {var="var" [scope="scope"] | varDom="var" [scope="scope"]} 
   [systemId="systemId"][filter="filter"]/>

// XML document specified via a String or Reader object
<x:parse doc="XMLDocument {var="var" [scope="scope"] | varDom="var" [scope="scope"]} 
   [systemId="systemId"][filter="filter"]>
    XML Document to parse
</x:parse>

Flow Control XML ActionsTop

There are five flow control XML actions, these being <x:if> action which allows us to process the body content if a condition evaluates to true. The <x:choose> action which works in a similar way to a Java switch statement when used in conjunction with the other two conditional actions; these being the <x:when> action which acts like a Java case statement and the <x:otherwise> action which acts like a Java default statement. The <c:forEach> action which evaluates the given XPath expression and repeats its nested body content over the result, setting the context node to each element in the iteration.

Action /
Attribute Name
Mandatory Run-time Expression? Default Value Object Type Description
<x:if>
selectYesNoNoneStringXPath expression to be evaluated.
If true body content is processed.
varNoNoNoneStringName of exported scoped variable to hold expression value.
The type of scoped variable is Boolean.
scopeNoNoPageStringScope of the scoped variable specified by var.
<x:choose>
The <x:choose> action contains no attributes although the body may contain one or more <x:when> actions and zero or one <x:otherwise> actions
<x:when>
selectYesNoNoneStringTest condition to be tested for.
If true body content is processed.
<x:otherwise>
No attributes
<x:forEach>
varNoNoNoneStringName of exported scoped variable to hold expression value.
The type of scoped variable is whatever type the select expression evaluates to.
selectYesNoNoneStringXPath expression to be evaluated.
If true body content is processed.
varStatusNoNoNoneStringName of exported scoped variable holding the status of the iteration which is of type javax.servlet.jsp.jstl.core.LoopTagStatus.
beginNoYesNoneintbegin attribute must be >= 0.
If items attribute specified then iteration begins at object located at specified index.
If items attribute not specified then iteration begins with value set by specified begin attribute.
endNoYesNoneintIf items attribute specified then iteration ends after object located at specified index.
If items attribute not specified then iteration ends at value set by specified end attribute.
stepNoYesNoneintstep attribute must be >= 1.
Iteration will only process every step item within the expression.

<x:if>Top

The <x:if> tag allows us to process the body content of the <x:if> tag if a condition evaluates to true and consists of two variants, with or without a body.

The following code snippets shows the two variants of the <x:if> tag where the square brackets indicate optional attributes and the curly bracers indicate a choice of options within them where the default is underlined.


// Evaluate XPath expression and save test condition result to var
<x:if select="XPathExpression" var="varName" [scope="{page|request|session|application}"]>

// Evaluate XPath expression and optionally save test condition result to var.
// Process body content if condition evaluates to true.
<x:if select="XPathExpression" [var="varName"] [scope="{page|request|session|application}"]>
    body content to process
</x:if>

<x:choose>Top

The <x:choose> tag is used in conjunction with the <x:when> and <x:otherwise> tags and works in a similar way to the switch .. case .. default Java conditional. There are two variants of the <x:choose> tag as shown in the code snippets below:


// <x:choose> and <x:when> 
<x:choose>
   <x:when select="XPathExpression">
      expression evaluates to true
   </x:when>
   <x:when select="XPathExpression">
      expression evaluates to true
   </x:when>
</x:choose>

// <x:choose>  <x:when> and <x:otherwise> 
<x:choose>
   <x:when select="XPathExpression">
      expression evaluates to true
   </x:when>
   <x:when select="XPathExpression">
      expression evaluates to true
   </x:when>
   <x:otherwise>
      no expressions have evaluated to true
   </x:otherwise>
</x:choose>

<x:forEach>Top

The <x:forEach> tag evaluates the given XPath expression and repeats its nested body content over the result, setting the context node to each element in the iteration.

The following code snippet shows the syntax of the <x:forEach> tag where the square brackets indicate optional attributes.


// Evaluates given XPath expression and iterate over body content
<x:forEach ["var="varName"] select="XPathExpression" ["varStatus="varStatusName"] 
           ["begin="begin"] ["end="end"] ["step="step"]> 
    body content
</x:forEach>

XML Transform ActionsTop

There are two transform XML actions, these being <x:transform> action which applies an XSLT stylesheet transformation to an XML document and the <c:param> action which sets transformation parameters as a nested action of <x:transform>.

Action /
Attribute Name
Mandatory Run-time Expression? Default Value Object Type Description
<x:transform>
docNoYesNoneString, Reader, javax.xml.transform.Source, org.w3c.dom.Document, or object exported by <x:parse>, <x:set>XPath expression to be evaluated.
The XML document to be transformed. If exported by <x:set>, it must be to a complete well-formed XML document.
xsltNoYesNoneString, Reader or javax.xml.transform.SourceTransformation stylesheet which must be a String, Reader, or Source object.
docSystemIdNoYesNoneStringURI for parsing the XML document.
varNoNoNoneStringName of exported scoped variable for the transform XML document.
The type of scoped variable is org.w3c.dom.Document.
scopeNoNoPageStringScope of the scoped variable specified by var.
resultNoYesNonejavax.xml.transform.ResultObject that captures or processes transformation result.
<x:param>
nameNoYesNoneStringTransformation parameter name.
valueNoYesNoneObjectTransformation parameter value.

<x:transform>Top

The <x:transform> action applies an XSLT stylesheet transformation to an XML document.

The following code snippets shows the tthree variants of the <x:if> tag where the square brackets indicate optional attributes and the curly bracers indicate a choice of options within them where the default is underlined.


// No body content
<x:transform doc="XMLDocument" [docSystemId="XMLSystemId"] [xsltSystemId="XSLTystemId"]
        [var="varName"] [scope="scope"] [result="resultObject"]>

// Body content specifying tranformation parameters
<x:transform doc="XMLDocument" [docSystemId="XMLSystemId"] [xsltSystemId="XSLTystemId"]
        [var="varName"] [scope="scope"] [result="resultObject"] >
    <c:param name="name" value="value">Somevalue</c:param>
</x:transform>

// Body content XML document and optional tranformation parameters
<x:transform doc="XMLDocument" [docSystemId="XMLSystemId"] [xsltSystemId="XSLTystemId"]
        [var="varName"] [scope="scope"] [result="resultObject"] >
     XML document to parse
    <c:param name="name" value="value">Somevalue</c:param>
</x:transform>

Lesson 3 Complete

In our second lesson on JSTL tag libraries we looked at the XML tag library.

What's Next?

In our third lesson on JSTL tag libraries we look at the Ii8n tag library.

go to home page Homepage go to top of page Top