Recipe 23.5: Using the XML Transform Tags

Problem

Solution

Use the various XML tags after declaring the tag library with the proper
taglib directive (uri attribute of http://java.sun.com/jstl/xml for JSTL 1.0 or http://java.sun.com/jsp/jstl/xml for JSTL 1.1).

Discussion

A number of web site teams may already have devised stylesheets for
transforming XML into HTML. In addition, you may want to separate most of the
XML transformation responsibilities from JSPs, so that JSPs focus only on
presenting the transformed information. The JSTL provides XML-related tags to
easily integrate stylesheets into JSPs. Example 23-4 is an Extensible Stylesheet Language (XSL) document that converts an XML file into HTML. The stylesheet provides a conversion of an Ant build file similar to the one described in Recipe 23.3.

How do you apply this XSL file to the build.xml file to produce a readable format? Example
23-5 uses the x:transform tag
to associate a stylesheet with an XML file. First, the JSP has to import both
the stylesheet of the prior example and the XML file this stylesheet transforms
by using the c:import tag. The c:import tag imports
the resource specified by its url attribute and stores it in a
variable (e.g., buildXml) that the x:transform tag can
access.

The x:transform tag makes the transformation process very easy,
once you've put together a valid stylesheet file. The x:transform tag's xml attribute specifies the XML file that the
x:transform tag handler transforms by applying a stylesheet. The
code specifies the stylesheet to use in the transformation with the
x:transform tag's
xslt attribute.

NOTE: The xml and xslt attributes of x:transform resolve the variables that represent the stylesheet and the XML file by using the EL, as in:

${buildXml}

Figure 23-3 shows the result of running the JSP of Example 23-5. In short, x:transform provides your very own XSLT processor for use in the JSP.

Figure 23-3. A JSP shows transformed XML content

See Also

The Jakarta Project's Taglibs site: http://jakarta.apache.org/taglibs/index.html; the Sun Microsystems JSTL information page: http://java.sun.com/products/jsp/jstl/; Recipe 23.2 on using the core tags; Recipe 23.3 on using the various XML-related tags; Recipe 23.5 on using the formatting tags; Recipe 23.6 and Recipe 23.7 on the JSTL's SQL features; Recipe 23.9-Recipe 23.14 on using the EL to access scoped variables, request headers and parameters, cookies, and JavaBean properties.

Check back here next week for more recipes from Java Servlet & JSP Cookbook. Excerpts will cover accessing an EJB from a servlet on WebLogic and connecting to Amazon Web Services (AWS) with a servlet or JSP.