Wednesday, June 22, 2005

Passing multiple XML documents into XSLT using JSTL

In case you ever want to pass multiple XML documents (nodesets) into a single XSLT for processing then the following simple example JSP page may be useful to you. All the XML and XSL needed is included in the page itself but could equally well be imported from elsewhere.


<%@ page contentType="text/html; charset=UTF-8" %><%--
--%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %><%--
--%>
<%@ taglib uri="http://java.sun.com/jstl/xml" prefix="x" %><%--

--%>
<c:set var="doc1">
<document>
<description>This is document one</description>
</document>
</c:set><%--

--%>
<x:parse varDom="doc2">
<document>
<description>This is document two</description>
</document>
</x:parse><%--

--%>
<x:parse varDom="doc3">
<document>
<description>This is document three</description>
</document>
</x:parse><%--

--%>
<c:set var="xslt">
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes" />
<xsl:param name="doc2"/>
<xsl:param name="doc3"/>

<xsl:template match="/">
<xsl:value-of select="/document/description" /><br />
<xsl:value-of select="$doc2/document/description" /><br />
<xsl:value-of select="$doc3/document/description" /><br />
</xsl:template>

</xsl:stylesheet>
</c:set><%--

--%>
<!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">
<head><title>Passing Nodesets into XSLT with JSTL Example</title></head>
<body>
<x:transform xml="${doc1}" xslt="${xslt}">
<x:param name="doc2" value="${doc2}" />
<x:param name="doc3" value="${doc3}" />
</x:transform>
</body>
</html>

2 comments:

Mark McLaren said...

Gr8!!!



But its that XML present then we applied XSLT.



What is the best way to fetch data from server as STRING buffer and then convert it into XML?
Note: Comment imported. Original by Prash at 2006-07-06 11:37

Mark McLaren said...

That depends on what you are dealing with! Assuming moderate complexity and that you are reading a file from another server then you could write a servlet to do this. First, get your text from the web.



If you expect the data to be in a recognised format such as JSON, iCalendar or CSV then you may be lucky enough to obtain a ready made parser for the format. Otherwise you would probably need to do a little bit of lexical analysis and parse the data yourself using something like the StreamTokenizer, StringTokenizer or Regular Expressions.





To convert the data into XML I like to use an XmlWriter class. Examples of these include osjava's xmlwriter and David Megginson's XMLWriter.





Let me know if you need more help... Mark


Note: Comment imported. Original by markmc website: http://cse-mjmcl.cse.bris.ac.uk/blog at 2006-07-06 17:07