JavaBlog.fr / Java.lu DEVELOPMENT,Java,WEB Java/XSL: XSLT with Xalan/JAXP

Java/XSL: XSLT with Xalan/JAXP

Here, a post to present briefly the recommandation XSL XSLT and some examples.

This article is a part of a serie of posts concerning the XSL recommendations.
From the W3C website about the The Extensible Stylesheet Language Family (XSL) http://www.w3.org/Style/XSL/:
XSL is a family of recommendations for defining XML document transformation and presentation. It consists of three parts:

  • XSL Transformations (XSLT): a language for transforming XML; An XSLT stylesheet specifies the presentation of a class of XML documents by describing how an instance of the class is transformed into an XML document that uses a formatting vocabulary, such as (X)HTML or XSL-FO. XSLT is developed by the W3C XSLT Working Group (members only) whose charter is to develop the next version of XSLT. XSLT is part of W3C’s XML Activity, whose work is described in the XML Activity Statement.
  • The XML Path Language (XPath): an expression language used by XSLT (and many other languages) to access or refer to parts of an XML document; XPath is developed jointly by the XQuery and XSLT Working Groups.
  • XSL Formatting Objects (XSL-FO): an XML vocabulary for specifying formatting semantics. XSL-FO is now developed by the XML Print and Page Layout Working Group.

Presentation
XSLT (eXtensible Stylesheet Language Transformations), defined in the W3C XSL recommendation is a language for transforming XML functional type. It allows to transform an XML document into another format such as HTML to be displayed as a web page. The main objective is the transformation of an XML document to a different schema or format (XHTML, HTML, XSL-FO, etc.).

However, XSLT also allows transformations to any other type of document in text format or in binary format (although this is not natively provided by the XSLT recommendation). Given two inputs, to transform an XML document and a XSLT document, an XSLT (XSLT processor) produces an output file in the desired format. XSLT relies on XPath (another part of the recommendation XSL) to designate a portion of an XML tree.

XSL can be used to define how an XML file should be displayed by transforming the XML file into a format such as HTML,…etc:

XSL Style Sheet
An XSL style sheet is a well-formed XML document. The root element <xsl:stylesheet> declares two namespaces: xsl for the XSL vocabulary and default for the target HTML, as follows:

 <?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns="http://www.w3.org/TR/REC-html40"
  version="1.0">
    ......
</xsl:stylesheet>

The bulk of the style sheet is a list of XSL template for matching with the source element and produce the target document. For example,

 <xsl:template match="HUOXml">
  <H2><xsl:apply-templates/></H2>
</xsl:template>

An XSL template consists of two parts:

  • A matching PATH in the match attribute, and
  • The action to be taken upon a successful match in the content of the template.

The XSLT tags
To generate content dynamically based on the contents of the source XML document, XSLT defined multiple tags with different behaviors. Here are the most used:

  • Template:
    <xsl:template match="expression XPath">
    ...
    </xsl:template>
    

    This is the most important tag of XSLT. It is thanks to it that the transformation to perform is defined. This tag allows to replace all parts of the XML document corresponding to the XPath expression by the contents of the tag.

  • Value-of:
    <xsl:value-of select="expression XPath"/>
    

    This tag will be replaced during processing by the content of the original document elements selected by the XPath expression. Thus, <xsl:value-of select="person/name"/> become the contents of the “name” son of “person” in the transformation.

  • For-each:
    <xsl:value-of select="expression XPath"/>
    

    The contents of this tag will be executed once for all elements of the original document that match the XPath expression. For example, it is possible to browse all elements “person” of a XML stream and extract/display the “name” element of each tag.

  • Sort:
    <xsl:sort select = "expression XPath"/>
    

    Placed inside a “for-each” tag, the “sort” tag allows to sort items listed by the “for-each” tag depending on the items selected by the XPath expression. Thus <xsl:sort select="name"/> placed in a “for-each” tag on the “person” will allow to scroll the list of “person” sorted by their names.

  • If:
    <xsl:if test="condition">
    ...
    </xsl:if>
    

    The contents of the tag will be executed only if the condition is true.

  • Apply:
    <xsl:apply-templates select = "expression XPath"/>
    

    Means to the XSLT processor to find templates and apply transformations associated to the elements identified by the XPath expression. If no expression is specified, the processor will look for templates for all current the elements and sub-elements.
    Warning: If no template is not for an item selected by the XPath expression, the processor apply to this element a kind of transformation “default” which is to replace the element by its content.

Many other tags exist and can perform complex transformations (see the site of W3Schools http://www.w3schools.com/xsl/). Nevertheless, the above tags are usually sufficient for most cases.

There are several implementations of XSLT parsers. In our examples, we use Xalan developed by the Apache Software Foundation. Xalan is in Java, C and Perl and manages XSLT 1.0.
From Apache http://xml.apache.org/xalan-j/:
Xalan-Java implements the javax.xml.transform interface in Java API for XML Processing (JAXP) 1.3. This interface provides a modular framework and a standard API for performing XML transformations, and utilizes system properties to determine which Transformer and which XML parser to use.

The necessary librairies JAR are:

  • xml-apis-1.0.b2.jar (TransformerFactory)
  • xalan-2.7.1.jar (TransformerFactoryImpl): Xalan 2 uses the JAXP API
  • serializer-2.7.1.jar (ExtendedContentHandler)

So, we are now able to study a concret case: (XML + XSL) =[ XSLT ]=> HTML
In the below examples, we will use the following xml File xmlFile.xml:

<?xml version="1.0" encoding="UTF-8"?>
<HUOXml VERSION="2" ID="HUO-DOCUMENT-ID">
	<DOCUMENT A.ID="JAVA-012345-2012">
		<DOCUMENT.HEADER>
			<A.TITLE>My Document Title - JavaBlog.fr / Java.lu</A.TITLE>
			<A.DATE DATE.VALUE="21.03.2012">(21 March 2012)</A.DATE>
		</DOCUMENT.HEADER>
		<CONTENTS CONTENTSID="HUO-CONTENTS-ID-123465">
			<A.P>Huseyin OZVEREN</A.P>
			<A.P>Java Development and Tools</A.P>
			<A.P>
				<A.DATE DATE.VALUE="21.03.2012">(21 March 2012)</A.DATE>
				<A.FONT CARACT="BUI">This is my first shot at blogging. </A.FONT><A.BRK/>I take this opportunity to introduce myself. 
				My name is Huseyin OZVEREN, I work currently like Senior Consultant J2EE in an IT services company in Europe. 
				Web development and Java passionate, I program with the Java Enterprise platform since 2003 by the definition 
				of multi-tier architecture systems and the production of high quality, readable, robust, documented and tested code.</A.P>
			<A.P><A.IMG SRC="http://www.w3.org/2008/site/images/logo-w3c-mobile-lg.png"/></A.P>
			<A.P><A.IMG SRC="http://www.w3.org/2012/08/Rome_sunset_banner-sm.jpg" HEIGHT="123" WIDTH="465"/></A.P>
			<A.P>
				<A.LIST TYPE="ListOfType1" LEVEL="1">
					<A.ITEM LEVEL="1" SYMBOL="1.">
						<A.P>LAW 1. text blabla bla bla </A.P>
					</A.ITEM>
					<A.ITEM LEVEL="1" SYMBOL="2.">
						<A.P>LAW 2. text blabla bla bla </A.P>
					</A.ITEM>
					<A.ITEM LEVEL="1" SYMBOL="3.">
						<A.P>LAW 3. text blabla bla bla </A.P>
					</A.ITEM>
					<A.ITEM LEVEL="1" SYMBOL="4.">
						<A.P>LAW 4. text blabla bla bla </A.P>
					</A.ITEM>
				</A.LIST>
			</A.P>
		</CONTENTS>
	</DOCUMENT>
</HUOXml>

Some explanations concerning this xml stream:

  • this xml stream is a document with a header and contents;
  • the root tag is HUOXml;
  • the document tag is DOCUMENT;
  • the document’s header tag is DOCUMENT.HEADER;
  • the document’s header contains a title A.TITLE and a date information A.DATE;
  • the document’s contents tag is CONTENTS;
  • the document’s contents are composed of paragraph A.P, date A.DATE, image A.IMG, line break A.BRK, list A.LIST and list’s items A.ITEM;
  • the document’s contents could be formatted by the font tag A.FONT having the attribute CARACT with the values ‘BUI’, ‘BI’, ‘BU’, ‘UI’, ‘B’, ‘U’, ‘I’, ‘SUB’, ‘SUP’: B for bold, I for Italic, U for underline…

Example n°1: (XML + XSL) =[XSLT processor]=> HTML
For this 1st example, we create the following style sheet (XSL) styleSheetXslFile.xsl to create a HTML output with the above XML stream:

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="2.0"
	xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fn="http://www.w3.org/2005/xpath-function">

	<xsl:output method="html" version="1.0" encoding="UTF-8"
		indent="yes" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
		doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" />

	<xsl:variable name="my_language">
		<xsl:text>en</xsl:text>
	</xsl:variable>
	<xsl:variable name="my_name">
		<xsl:text>Huseyin Ozveren</xsl:text>
	</xsl:variable>

	<xsl:template name="hello_lang">
		<xsl:param name="currentLanguage" select="fr" />
		<xsl:choose>
			<xsl:when test="$currentLanguage = 'fr'">
				<xsl:text>Bonjour</xsl:text>
			</xsl:when>
			<xsl:when test="$currentLanguage = 'en'">
				<xsl:text>Hello</xsl:text>
			</xsl:when>
			<xsl:when test="$currentLanguage = 'bg'">
				<xsl:text>здравейте</xsl:text>
			</xsl:when>
			<xsl:when test="$currentLanguage = 'cs'">
				<xsl:text>ahoj</xsl:text>
			</xsl:when>
			<xsl:when test="$currentLanguage = 'de'">
				<xsl:text>Hallo</xsl:text>
			</xsl:when>
			<xsl:when test="$currentLanguage = 'el'">
				<xsl:text>γειά σου</xsl:text>
			</xsl:when>
			<xsl:when test="$currentLanguage = 'es'">
				<xsl:text>¡hola</xsl:text>
			</xsl:when>
			<xsl:when test="$currentLanguage = 'it'">
				<xsl:text>ciao</xsl:text>
			</xsl:when>
			<xsl:otherwise>
				<xsl:message terminate="yes">
					<xsl:text>Language code not defined : </xsl:text>
					<xsl:value-of select="$currentLanguage" />
				</xsl:message>
			</xsl:otherwise>
		</xsl:choose>
	</xsl:template>

	<!-- root -->
	<xsl:template match="HUOXml">
		<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
			<head>
				<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
				<meta http-equiv="Content-Language" content="fr" />
				<title>
					JavaBlog.fr - Java.lu
					<xsl:call-template name="hello_lang">
						<xsl:with-param name="currentLanguage">
							<xsl:copy-of select="$my_language" />
						</xsl:with-param>
					</xsl:call-template>
				</title>
				<meta name="description" content="" />
				<meta name="keywords" content="java, spring, javablog, fr, hibernate, lu, gwt" />
				<meta name="language" content="fr" />
				<meta name="available" content="03-03-2010" />
				<meta name="robots"
					content="index, follow, noodp, noydir, noarchive, notranslate" />
				<meta name="sipade-leg" content="7" />
			</head>
			<body>

				<div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"> </div>

				<a name="top"></a>

				<table cellpadding="0" cellspacing="0" border="0" width="100%">
					<tr>
						<td style="padding:10px;">
							<table width="100%" border="0" cellpadding="5" cellspacing="0">
								<tr>
									<td colspan="2" align="left" valign="top" style="padding: 5px;"></td>
								</tr>
								<tr valign="top" bgcolor="#F5F5F5">
									<td align="left" style="padding: 5px;">
										<!-- Date of document -->
										<xsl:value-of
											select="substring(//HUOXml/DOCUMENT/DOCUMENT.HEADER/A.TITLE/A.DATE, 2, string-length(//HUOXml/DOCUMENT/DOCUMENT.HEADER/A.TITLE/A.DATE) -2) " />
									</td>
									<td align="right" style="padding: 5px;">
										<table border="0" align="right" cellpadding="0"
											cellspacing="0">
											<tr>
												<td nowrap="nowrap">
													<span>
														<!-- Number and Year -->
														<xsl:text>123456</xsl:text>
														<xsl:text>/</xsl:text>
														<xsl:text>2012</xsl:text>
													</span>
												</td>
											</tr>
										</table>
									</td>
								</tr>

								<tr valign="top">
									<td align="left" style="padding: 5px;">
										<xsl:apply-templates select="//HUOXml/DOCUMENT/DOCUMENT.HEADER" />
									</td>
									<td align="right">
										<b>
											<xsl:value-of
												select="translate($my_name, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')" />
										</b>
									</td>
								</tr>

								<tr valign="top" align="left">
									<td colspan="2" align="left" style="padding: 5px;">
										<xsl:apply-templates select="//HUOXml/DOCUMENT/CONTENTS" />
									</td>
								</tr>
							</table>
						</td>
					</tr>
				</table>
			</body>
		</html>
	</xsl:template>


	<!-- Header -->
	<xsl:template match="DOCUMENT.HEADER/A.TITLE">
	</xsl:template>

	<!-- Content -->
	<xsl:template match="A.P">
		<p align="left" style="margin:8px 0px; line-height:18px;">
			<xsl:apply-templates />
		</p>
	</xsl:template>
	<xsl:template match="A.BRK">
		<br />
	</xsl:template>

	<xsl:template match="A.FONT[@CARACT]">
		<xsl:choose>
			<xsl:when test="@CARACT = 'BUI'">
				<b>
					<u>
						<i>
							<xsl:apply-templates />
						</i>
					</u>
				</b>
			</xsl:when>
			<xsl:when test="@CARACT = 'BI'">
				<b>
					<i>
						<xsl:apply-templates />
					</i>
				</b>
			</xsl:when>
			<xsl:when test="@CARACT = 'BU'">
				<b>
					<u>
						<xsl:apply-templates />
					</u>
				</b>
			</xsl:when>
			<xsl:when test="@CARACT = 'UI'">
				<u>
					<i>
						<xsl:apply-templates />
					</i>
				</u>
			</xsl:when>
			<xsl:when test="@CARACT = 'B'">
				<b>
					<xsl:apply-templates />
				</b>
			</xsl:when>
			<xsl:when test="@CARACT = 'U'">
				<u>
					<xsl:apply-templates />
				</u>
			</xsl:when>
			<xsl:when test="@CARACT = 'I'">
				<i>
					<xsl:apply-templates />
				</i>
			</xsl:when>
			<xsl:when test="@CARACT = 'SUB'">
				<sub>
					<xsl:apply-templates />
				</sub>
			</xsl:when>
			<xsl:when test="@CARACT = 'SUP'">
				<sup>
					<xsl:apply-templates />
				</sup>
			</xsl:when>
			<xsl:otherwise>
				<xsl:apply-templates />
			</xsl:otherwise>
		</xsl:choose>
	</xsl:template>

	<xsl:template match="A.IMG">
		<img>
			<xsl:attribute name="src"><xsl:value-of select='@SRC' /></xsl:attribute>

			<xsl:choose>
				<xsl:when test="@HEIGHT">
					<xsl:attribute name="height"><xsl:value-of
						select='@HEIGHT' /></xsl:attribute>
				</xsl:when>
				<xsl:otherwise></xsl:otherwise>
			</xsl:choose>

			<xsl:choose>
				<xsl:when test="@WIDTH">
					<xsl:attribute name="width"><xsl:value-of
						select='@WIDTH' /></xsl:attribute>
				</xsl:when>
				<xsl:otherwise></xsl:otherwise>
			</xsl:choose>

		</img>
	</xsl:template>

	<xsl:template match="A.TABLE">
		<center>
			<table>
				<xsl:apply-templates />
			</table>
		</center>
	</xsl:template>

	<xsl:template match="CAPTION|COL|COLGROUP|THEAD|TFOOT|TBODY|TR|TH|TD">
		<xsl:copy>
			<xsl:apply-templates select="@*" />
			<xsl:apply-templates />
		</xsl:copy>
	</xsl:template>
	<xsl:template match="A.TABLE//@*">
		<xsl:copy>
			<xsl:apply-templates select="@*" />
			<xsl:apply-templates />
		</xsl:copy>
	</xsl:template>


	<!-- Lists -->
	<xsl:template match="A.LIST">
		<table border="0" width="100%" cellpadding="0" cellspacing="0">
			<xsl:apply-templates select="./A.ITEM" />
		</table>
	</xsl:template>

	<xsl:template match="A.LIST/A.ITEM">
		<tr valign="top">
			<td width="3%">
			</td>
			<xsl:apply-templates />
		</tr>
	</xsl:template>

	<xsl:template match="A.LIST/A.ITEM/SYMBOL">
		<td width="3%">
			<xsl:apply-templates />
		</td>
	</xsl:template>
	<xsl:template match="A.LIST/A.ITEM/A.P[position()=1]">
		<td>
			<xsl:apply-templates />
		</td>
	</xsl:template>
	<xsl:template match="A.LIST/A.ITEM/A.P[position()>1]">
		<tr>
			<td></td>
			<td>
				<xsl:apply-templates />
			</td>
		</tr>
	</xsl:template>

</xsl:stylesheet>

Some explanations concerning this style sheet:

  • we define the ouput type xsl:output method=”html” and the version of stylesheet xsl:stylesheet version=”2.0″;
  • the variables my_language and my_name are declared;
  • the entry point of this style sheet is the root tag is xsl:template match=”HUOXml”>;
  • then, similar instructions are defined for each tag in xml stream;
  • the instructions for the document’s header tag are xsl:apply-templates select=”//HUOXml/DOCUMENT/DOCUMENT.HEADER” ;
  • the instructions for the document’s contents tag are xsl:apply-templates select=”//HUOXml/DOCUMENT/CONTENTS”;

The Java code for the XSL processing is:

/**
 * Generate HTML = XSL stylesheet + XML file
 * Without parameters from XLST processors
 * 
 * @author Huseyin OZVEREN
 *
 */
public class TestGenerateHTMLWithOutParams {

	public static void main(String[] args) {
		String xmlPathFile = "xmlFile.xml";
		String xslPathFile = "styleSheetXslFile.xsl";
		System.out.println(buildHtml(xmlPathFile, xslPathFile));
	} 
	
	/**
	 * Builds the HTML from XSL + XML
	 * @return html document
	 */
	public static String buildHtml(String xmlPathFile, String xslPathFile)  {

		ByteArrayOutputStream htmlStreamResult = null;

		try {
			// XML Stream
			InputStream xmlStream = TestGenerateHTMLWithOutParams.class.getResourceAsStream(xmlPathFile);
	        Source sourceXml = new StreamSource(xmlStream);
	        
			// XSL Stream
	        InputStream xslStream = TestGenerateHTMLWithOutParams.class.getResourceAsStream(xslPathFile);
	        Source sourceXsl = new StreamSource(xslStream);
			
	        // HTML Stream
	        htmlStreamResult = new ByteArrayOutputStream();

	        // transform
	        TransformerFactory tFactory = TransformerFactory.newInstance();
		    Transformer transformer = tFactory.newTransformer(sourceXsl);
		    transformer.transform(sourceXml, new javax.xml.transform.stream.StreamResult(htmlStreamResult));

		    
		    return htmlStreamResult.toString().replaceAll("\u2005", " ").replaceAll("\u2009", " ");
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != htmlStreamResult)
					htmlStreamResult.close();
			} catch (Throwable e) {
			} // end-try
		} // end-try
		
		return null;
	}
}

So, we could obtain the following ouputs in console:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fn="http://www.w3.org/2005/xpath-function" lang="fr" xml:lang="fr">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
<meta content="fr" http-equiv="Content-Language" />
<title>
					JavaBlog.fr - Java.lu
					Hello</title>
<meta content="" name="description" />
<meta content="java, spring, javablog, fr, hibernate, lu, gwt" name="keywords" />
<meta content="fr" name="language" />
<meta content="03-03-2010" name="available" />
<meta content="index, follow, noodp, noydir, noarchive, notranslate" name="robots" />
<meta content="7" name="sipade-leg" />
</head>
<body>
<div style="position:absolute; visibility:hidden; z-index:1000;" id="overDiv">&nbsp;</div>
<a name="top" />
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td style="padding:10px;">
<table cellspacing="0" cellpadding="5" border="0" width="100%">
<tr>
<td style="padding: 5px;" valign="top" align="left" colspan="2" />
</tr>
<tr bgcolor="#F5F5F5" valign="top">
<td style="padding: 5px;" align="left" />
<td style="padding: 5px;" align="right">
<table cellspacing="0" cellpadding="0" align="right" border="0">
<tr>
<td nowrap="nowrap">
<span>123456/2012</span>
</td>
</tr>
</table>
</td>
</tr>
<tr valign="top">
<td style="padding: 5px;" align="left">
			
			(21 March 2012)
		</td>
<td align="right">
<b>HUSEYIN OZVEREN</b>
</td>
</tr>
<tr align="left" valign="top">
<td style="padding: 5px;" align="left" colspan="2">
			
<p xmlns="" style="margin:8px 0px; line-height:18px;" align="left">Huseyin OZVEREN</p>
			
<p style="margin:8px 0px; line-height:18px;" align="left">Java Development and Tools</p>
			
<p style="margin:8px 0px; line-height:18px;" align="left">
				(21 March 2012)
				<b><u><i>This is my first shot at blogging. </i></u></b>
<br>I take this opportunity to introduce myself. 
				My name is Huseyin OZVEREN, I work currently like Senior Consultant J2EE in an IT services company in Europe. 
				Web development and Java passionate, I program with the Java Enterprise platform since 2003 by the definition 
				of multi-tier architecture systems and the production of high quality, readable, robust, documented and tested code.</p>
			
<p style="margin:8px 0px; line-height:18px;" align="left">
<img src="http://www.w3.org/2008/site/images/logo-w3c-mobile-lg.png"></p>
			
<p style="margin:8px 0px; line-height:18px;" align="left">
<img src="http://www.w3.org/2012/08/Rome_sunset_banner-sm.jpg" height="123" width="465"></p>
			
<p style="margin:8px 0px; line-height:18px;" align="left">
				
<table cellspacing="0" cellpadding="0" width="100%" border="0">
<tr valign="top">
<td width="3%"></td>
						<td>LAW 1. text blabla bla bla </td>
					
</tr>
<tr valign="top">
<td width="3%"></td>
						<td>LAW 2. text blabla bla bla </td>
					
</tr>
<tr valign="top">
<td width="3%"></td>
						<td>LAW 3. text blabla bla bla </td>
					
</tr>
<tr valign="top">
<td width="3%"></td>
						<td>LAW 4. text blabla bla bla </td>
					
</tr>
</table>
			
</p>
		</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>

…and in the browser:

The W3 SCHOOLS site proposes a tool to try your XSL style sheet and XML streams at the URL
http://www.w3schools.com/xsl/tryxslt.asp?xmlfile=cdcatalog&xsltfile=cdcatalog_ex1, so with our example:

Example n°2 with params: (XML + XSL) =[XSLT processor]=> HTML
For this 2nd example, we will modify our style sheet (XSL) styleSheetXslFile.xsl in order to create a HTML output with expected parameters the above XML stream:

...
	<xsl:param name="MY.PARAMS.LANGUAGE"></xsl:param>
	<xsl:param name="MY.PARAMS.NAME"></xsl:param>
	<xsl:param name="MY.PARAMS.YEAR"></xsl:param>
	<xsl:param name="MY.PARAMS.NUMBER"></xsl:param>
...

…the variable my_language will contain the value of the parameter MY.PARAMS.LANGUAGE,
…the variable my_name will contain the value of the parameter MY.PARAMS.NAME,
…more, the date and number were hard-coded in the XSL like:

...
<!-- Number and Year -->
<xsl:text>123456</xsl:text>
<xsl:text>/</xsl:text>
<xsl:text>2012</xsl:text>
...

…now, these informations will be displayed from the parameters MY.PARAMS.NUMBER and MY.PARAMS.YEAR.

The new style sheet (XSL) styleSheetXslFile.xsl is:

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="2.0"
	xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fn="http://www.w3.org/2005/xpath-function">

	<xsl:output method="html" version="1.0" encoding="UTF-8"
		indent="yes" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
		doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" />

	<xsl:param name="MY.PARAMS.LANGUAGE"></xsl:param>
	<xsl:param name="MY.PARAMS.NAME"></xsl:param>
	<xsl:param name="MY.PARAMS.YEAR"></xsl:param>
	<xsl:param name="MY.PARAMS.NUMBER"></xsl:param>

	<xsl:variable name="my_language">
		<xsl:value-of
			select="translate($MY.PARAMS.LANGUAGE, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')" />
	</xsl:variable>
	<xsl:variable name="my_name">
		<xsl:value-of
			select="translate($MY.PARAMS.NAME, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')" />
	</xsl:variable>

	<xsl:template name="hello_lang">
		<xsl:param name="currentLanguage" select="fr" />
		<xsl:choose>
			<xsl:when test="$currentLanguage = 'fr'">
				<xsl:text>Bonjour</xsl:text>
			</xsl:when>
			<xsl:when test="$currentLanguage = 'en'">
				<xsl:text>Hello</xsl:text>
			</xsl:when>
			<xsl:when test="$currentLanguage = 'bg'">
				<xsl:text>здравейте</xsl:text>
			</xsl:when>
			<xsl:when test="$currentLanguage = 'cs'">
				<xsl:text>ahoj</xsl:text>
			</xsl:when>
			<xsl:when test="$currentLanguage = 'de'">
				<xsl:text>Hallo</xsl:text>
			</xsl:when>
			<xsl:when test="$currentLanguage = 'el'">
				<xsl:text>γειά σου</xsl:text>
			</xsl:when>
			<xsl:when test="$currentLanguage = 'es'">
				<xsl:text>¡hola</xsl:text>
			</xsl:when>
			<xsl:when test="$currentLanguage = 'it'">
				<xsl:text>ciao</xsl:text>
			</xsl:when>
			<xsl:otherwise>
				<xsl:message terminate="yes">
					<xsl:text>Language code not defined : </xsl:text>
					<xsl:value-of select="$currentLanguage" />
				</xsl:message>
			</xsl:otherwise>
		</xsl:choose>
	</xsl:template>

	<!-- root -->
	<xsl:template match="HUOXml">
		<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
			<head>
				<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
				<meta http-equiv="Content-Language" content="fr" />
				<title>
					JavaBlog.fr - Java.lu
					<xsl:call-template name="hello_lang">
						<xsl:with-param name="currentLanguage">
							<xsl:copy-of select="$my_language" />
						</xsl:with-param>
					</xsl:call-template>
				</title>
				<meta name="description" content="" />
				<meta name="keywords" content="java, spring, javablog, fr, hibernate, lu, gwt" />
				<meta name="language" content="fr" />
				<meta name="available" content="03-03-2010" />
				<meta name="robots"
					content="index, follow, noodp, noydir, noarchive, notranslate" />
				<meta name="sipade-leg" content="7" />
			</head>
			<body>

				<div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"> </div>

				<a name="top"></a>

				<table cellpadding="0" cellspacing="0" border="0" width="100%">
					<tr>
						<td style="padding:10px;">
							<table width="100%" border="0" cellpadding="5" cellspacing="0">
								<tr>
									<td colspan="2" align="left" valign="top" style="padding: 5px;"></td>
								</tr>
								<tr valign="top" bgcolor="#F5F5F5">
									<td align="left" style="padding: 5px;">
										<!-- Date of document -->
										<xsl:value-of
											select="substring(//HUOXml/DOCUMENT/DOCUMENT.HEADER/A.TITLE/A.DATE, 2, string-length(//HUOXml/DOCUMENT/DOCUMENT.HEADER/A.TITLE/A.DATE) -2) " />
									</td>
									<td align="right" style="padding: 5px;">
										<table border="0" align="right" cellpadding="0"
											cellspacing="0">
											<tr>
												<td nowrap="nowrap">
													<span>
														<!-- Number and Year -->
														<xsl:value-of select="$MY.PARAMS.NUMBER" />
														<xsl:text>/</xsl:text>
														<xsl:value-of select="$MY.PARAMS.YEAR" />
													</span>
												</td>
											</tr>
										</table>
									</td>
								</tr>

								<tr valign="top">
									<td align="left" style="padding: 5px;">
										<xsl:apply-templates select="//HUOXml/DOCUMENT/DOCUMENT.HEADER" />
									</td>
									<td align="right">
										<b>
											<xsl:value-of
												select="translate($my_name, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')" />
										</b>
									</td>
								</tr>

								<tr valign="top" align="left">
									<td colspan="2" align="left" style="padding: 5px;">
										<xsl:apply-templates select="//HUOXml/DOCUMENT/CONTENTS" />
									</td>
								</tr>
							</table>
						</td>
					</tr>
				</table>
			</body>
		</html>
	</xsl:template>


	<!-- Header -->
	<xsl:template match="DOCUMENT.HEADER/A.TITLE">
	</xsl:template>

	<!-- Content -->
	<xsl:template match="A.P">
		<p align="left" style="margin:8px 0px; line-height:18px;">
			<xsl:apply-templates />
		</p>
	</xsl:template>
	<xsl:template match="A.BRK">
		<br />
	</xsl:template>

	<xsl:template match="A.FONT[@CARACT]">
		<xsl:choose>
			<xsl:when test="@CARACT = 'BUI'">
				<b>
					<u>
						<i>
							<xsl:apply-templates />
						</i>
					</u>
				</b>
			</xsl:when>
			<xsl:when test="@CARACT = 'BI'">
				<b>
					<i>
						<xsl:apply-templates />
					</i>
				</b>
			</xsl:when>
			<xsl:when test="@CARACT = 'BU'">
				<b>
					<u>
						<xsl:apply-templates />
					</u>
				</b>
			</xsl:when>
			<xsl:when test="@CARACT = 'UI'">
				<u>
					<i>
						<xsl:apply-templates />
					</i>
				</u>
			</xsl:when>
			<xsl:when test="@CARACT = 'B'">
				<b>
					<xsl:apply-templates />
				</b>
			</xsl:when>
			<xsl:when test="@CARACT = 'U'">
				<u>
					<xsl:apply-templates />
				</u>
			</xsl:when>
			<xsl:when test="@CARACT = 'I'">
				<i>
					<xsl:apply-templates />
				</i>
			</xsl:when>
			<xsl:when test="@CARACT = 'SUB'">
				<sub>
					<xsl:apply-templates />
				</sub>
			</xsl:when>
			<xsl:when test="@CARACT = 'SUP'">
				<sup>
					<xsl:apply-templates />
				</sup>
			</xsl:when>
			<xsl:otherwise>
				<xsl:apply-templates />
			</xsl:otherwise>
		</xsl:choose>
	</xsl:template>

	<xsl:template match="A.IMG">
		<img>
			<xsl:attribute name="src"><xsl:value-of select='@SRC' /></xsl:attribute>

			<xsl:choose>
				<xsl:when test="@HEIGHT">
					<xsl:attribute name="height"><xsl:value-of
						select='@HEIGHT' /></xsl:attribute>
				</xsl:when>
				<xsl:otherwise></xsl:otherwise>
			</xsl:choose>

			<xsl:choose>
				<xsl:when test="@WIDTH">
					<xsl:attribute name="width"><xsl:value-of
						select='@WIDTH' /></xsl:attribute>
				</xsl:when>
				<xsl:otherwise></xsl:otherwise>
			</xsl:choose>

		</img>
	</xsl:template>

	<xsl:template match="A.TABLE">
		<center>
			<table>
				<xsl:apply-templates />
			</table>
		</center>
	</xsl:template>

	<xsl:template match="CAPTION|COL|COLGROUP|THEAD|TFOOT|TBODY|TR|TH|TD">
		<xsl:copy>
			<xsl:apply-templates select="@*" />
			<xsl:apply-templates />
		</xsl:copy>
	</xsl:template>
	<xsl:template match="A.TABLE//@*">
		<xsl:copy>
			<xsl:apply-templates select="@*" />
			<xsl:apply-templates />
		</xsl:copy>
	</xsl:template>


	<!-- Lists -->
	<xsl:template match="A.LIST">
		<table border="0" width="100%" cellpadding="0" cellspacing="0">
			<xsl:apply-templates select="./A.ITEM" />
		</table>
	</xsl:template>

	<xsl:template match="A.LIST/A.ITEM">
		<tr valign="top">
			<td width="3%">
			</td>
			<xsl:apply-templates />
		</tr>
	</xsl:template>

	<xsl:template match="A.LIST/A.ITEM/SYMBOL">
		<td width="3%">
			<xsl:apply-templates />
		</td>
	</xsl:template>
	<xsl:template match="A.LIST/A.ITEM/A.P[position()=1]">
		<td>
			<xsl:apply-templates />
		</td>
	</xsl:template>
	<xsl:template match="A.LIST/A.ITEM/A.P[position()>1]">
		<tr>
			<td></td>
			<td>
				<xsl:apply-templates />
			</td>
		</tr>
	</xsl:template>

</xsl:stylesheet>

The new Java code for the XSL processing is:

/**
 * Generate HTML = XSL stylesheet + XML file
 * Without parameters from XLST processors
 * 
 * @author Huseyin OZVEREN
 */

public class TestGenerateHTMLWithParams {

	public static void main(String[] args) {
		String xmlPathFile = "xmlFile.xml";
		String xslPathFile = "styleSheetXslFile.xsl";

		System.out.println(buildHtml(xmlPathFile, xslPathFile));
	} 
	
	/**
	 * Builds the HTML from XSL + XML
	 * @return html document
	 */
	public static String buildHtml(String xmlPathFile, String xslPathFile)  {

		ByteArrayOutputStream htmlStreamResult = null;

		try {
			// XML Stream
			InputStream xmlStream = TestGenerateHTMLWithParams.class.getResourceAsStream(xmlPathFile);
	        Source sourceXml = new StreamSource(xmlStream);
	        
			// XSL Stream
	        InputStream xslStream = TestGenerateHTMLWithParams.class.getResourceAsStream(xslPathFile);
	        Source sourceXsl = new StreamSource(xslStream);
			
	        // HTML Stream
	        htmlStreamResult = new ByteArrayOutputStream();

	        // transform
	        TransformerFactory tFactory = TransformerFactory.newInstance();
		    Transformer transformer = tFactory.newTransformer(sourceXsl);
		    transformer.setParameter("MY.PARAMS.LANGUAGE", "FR");
	    	transformer.setParameter("MY.PARAMS.NAME", "Bill Gates");
		    transformer.setParameter("MY.PARAMS.YEAR", "9999");
		    transformer.setParameter("MY.PARAMS.NUMBER", "XX1245XX" );
		    transformer.transform(sourceXml, new javax.xml.transform.stream.StreamResult(htmlStreamResult));
		    
		    return htmlStreamResult.toString().replaceAll("\u2005", " ").replaceAll("\u2009", " ");
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != htmlStreamResult)
					htmlStreamResult.close();
			} catch (Throwable e) {
			} // end-try
		} // end-try
		
		return null;
	}	
}

So, we could obtain the following ouputs in console:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fn="http://www.w3.org/2005/xpath-function" lang="fr" xml:lang="fr">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
<meta content="fr" http-equiv="Content-Language" />
<title>
					JavaBlog.fr - Java.lu
					Bonjour</title>
<meta content="" name="description" />
<meta content="java, spring, javablog, fr, hibernate, lu, gwt" name="keywords" />
<meta content="fr" name="language" />
<meta content="03-03-2010" name="available" />
<meta content="index, follow, noodp, noydir, noarchive, notranslate" name="robots" />
<meta content="7" name="sipade-leg" />
</head>
<body>
<div style="position:absolute; visibility:hidden; z-index:1000;" id="overDiv">&nbsp;</div>
<a name="top" />
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td style="padding:10px;">
<table cellspacing="0" cellpadding="5" border="0" width="100%">
<tr>
<td style="padding: 5px;" valign="top" align="left" colspan="2" />
</tr>
<tr bgcolor="#F5F5F5" valign="top">
<td style="padding: 5px;" align="left" />
<td style="padding: 5px;" align="right">
<table cellspacing="0" cellpadding="0" align="right" border="0">
<tr>
<td nowrap="nowrap">
<span>XX1245XX/9999</span>
</td>
</tr>
</table>
</td>
</tr>
<tr valign="top">
<td style="padding: 5px;" align="left">
			
			(21 March 2012)
		</td>
<td align="right">
<b>BILL GATES</b>
</td>
</tr>
<tr align="left" valign="top">
<td style="padding: 5px;" align="left" colspan="2">
			
<p xmlns="" style="margin:8px 0px; line-height:18px;" align="left">Huseyin OZVEREN</p>
			
<p style="margin:8px 0px; line-height:18px;" align="left">Java Development and Tools</p>
			
<p style="margin:8px 0px; line-height:18px;" align="left">
				(21 March 2012)
				<b><u><i>This is my first shot at blogging. </i></u></b>
<br>I take this opportunity to introduce myself. 
				My name is Huseyin OZVEREN, I work currently like Senior Consultant J2EE in an IT services company in Europe. 
				Web development and Java passionate, I program with the Java Enterprise platform since 2003 by the definition 
				of multi-tier architecture systems and the production of high quality, readable, robust, documented and tested code.</p>
			
<p style="margin:8px 0px; line-height:18px;" align="left">
<img src="http://www.w3.org/2008/site/images/logo-w3c-mobile-lg.png"></p>
			
<p style="margin:8px 0px; line-height:18px;" align="left">
<img src="http://www.w3.org/2012/08/Rome_sunset_banner-sm.jpg" height="123" width="465"></p>
			
<p style="margin:8px 0px; line-height:18px;" align="left">
				
<table cellspacing="0" cellpadding="0" width="100%" border="0">
<tr valign="top">
<td width="3%"></td>
						<td>LAW 1. text blabla bla bla </td>
					
</tr>
<tr valign="top">
<td width="3%"></td>
						<td>LAW 2. text blabla bla bla </td>
					
</tr>
<tr valign="top">
<td width="3%"></td>
						<td>LAW 3. text blabla bla bla </td>
					
</tr>
<tr valign="top">
<td width="3%"></td>
						<td>LAW 4. text blabla bla bla </td>
					
</tr>
</table>
			
</p>
		</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>

…and in the browser:

In this post, I have presented briefly the recommandation XSLT of XSL with the XSL processor XALAN to create HTML from XML stream and XSL stylesheet. More, I have exposed examples with/without parameters passed from XSL processor to XSL stylesheet.

Source: test_xml_xslt.zip

That’s all!!!

Huseyin OZVEREN

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

Related Post