Working with XML

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

As far as technologies go, XML does, by all accounts, carry a lot of hype. As Java brings programmers the reality of platform-neutral programming, XML brings us the interesting prospect of platform-neutral data. In this article, I’ll examine how Extensible Stylesheet Language Transformations (XSLT) can be used to manipulate data contained in an XML document, and how it can be used to publish standard HTML. I’ll also give an example of how you can use WebSphere’s LotusXSL to transform XML into HTML.

In a nutshell, XML is merely a way to represent data. All by itself, XML doesn’t really do anything other than bring together data in a structured format. To do something with it, low-level APIs like Document Object Model (DOM) or SAX are typically used to create, parse, or traverse an XML document. Parser packages like XML4J from IBM or Project X from Sun attempt to create a higher-level interface for programmers and are successful in doing so. Another method of manipulating XML documents bears consideration, not only for its ease of use, but for the robust features it brings to the e- commerce development community. The method I’m referring to is XSLT.

Here’s a quick synopsis of what’s what in the XML/XSLT world. In order to use XSLT, you’ll need an XSL processor. For WebSphere, this means the LotusXSL processor that can be found in the lotusxsl.jar file in WebSphere’s class path—although XSL processors can be found for both the server side and the client side. For example, Microsoft’s MSXML can be installed on the client machine to support XML transformations. The LotusXSL processor ships with WebSphere, but updates and source code can be found at IBM’s alphaWorks Web site (http://alphaworks.ibm.com/aw.nsf/ techmain/lotusxsl). By now, you might feel a little fuzzy about the key technologies mentioned so far. There’s XML, XSLT, and XSL. To make things even murkier, I’ll bring up XPath. XPath is a separate specification by the World Wide Web Consortium (W3C), but it is used within XSLT for the format of expressions acting as some sort of sublanguage. For example, the XPath function count() is used to determine the number of nodes in a particular tree. So, if we had an XML document with a root element of with several child nodes, the following XSLT element would return the number of employees:


XSLT has been referred to as a language that is similar in functionality to SQL, in that it is a data manipulation language. There are, of course, differences—but simplicity in formatting data is the common ground.

Now, let’s take a look at the example. In the example, a servlet uses Java Database Connectivity (JDBC) to extract database information, creates well-formed XML from the ResultSet, and then transforms that XML document into HTML with the help of the LotusXSL processor and an XSL stylesheet. Once the XML document has been cached, I can sort the tabular data simply by clicking on the column headings. Figure 1 shows a screen shot of the working example, which can be downloaded at www.midrangecomputing.com/mc.

First, take a look at the servlet. In Figure 2 (page 64), Section A, you can see the snippet that creates the XML. Earlier, I called it an XML document, but, in Java-specific terms, it’s not a DOM Document object but an ordinary String object. As you can see, I just iterate through the ResultSet, grab the column name for the element name, and insert the column’s value as the element’s value. The reason I can use a simple String object is because I can easily use it to create a java.io.Reader in the form of a StringReader. A Reader object can be used, in turn, to create an XSLTInputSource object, which is required in the process() method of the XSLTProcessor. If all that sounds confusing, just take a look at Figure 2, Section B, which shows the relatively few lines of code required to transform XML within a servlet using the LotusXSL processor. To briefly recap that code, you’ll need two XSLTInputSource objects and an XSLTResultTarget object for the XSL processor to function. The two input sources will be an XML document that you created from the ResultSet and an XSL stylesheet. The result target will be the servlet’s response OutputStream.

Now, take a look at that XSL stylesheet. To get a grip on how stylesheets work with XML documents and XSL processors to transform XML, I’ll review a little of JavaServer Page (JSP) 101. We know that we can mix Java source with HTML and, in the end, users will see the conditioned or calculated HTML output in the browser. The same basic principle exists when using XSL stylesheets. If you would like to transform your XML into HTML, as in the example, embed HTML within the XSL stylesheet. This is another effective means in the ongoing effort to separate business logic from presentation logic within an application. Also within the XSL stylesheet would be XSLT elements, as shown in Figure 3, Section A. That particular code snippet shows the xsl:value-of element in between standard HTML tags. This lets the XSL processor know to insert the value of a particular XML element in its output.

As you can see, XSLT elements are represented in tag format, making it easier for non-programmers to manage the presentation responsibilities of an application. In the accompanying example, users will be able to click on the column headings to sort the table of data. Two parameters are passed from the query string in the URL to the servlet and then to the XSL stylesheet. At first, it might seem unnatural to be able to pass a parameter to a static document such as an XSL stylesheet, but it is, in fact, the responsibility of the XSL processor to handle those parameters. The parameters are the column you want to sort and the data type of the column. I pass the data type explicitly, because after I format the numeric columns (Figure 3, Section A), the XSL processor will look at that data as text, and the sort won’t give the desired effect. Figure 3, Section B shows the iteration the XSL stylesheet goes through to determine the desired sort and the data type of the column.

Going back to the beginning of the example, the servlet creates the database connection and gets the data in its init() method. It then stores the XML document in memory so that the sort is almost instant. The problem, as you can see, is that for large amounts of data, this method is impractical. Which brings me to a quick discussion on what XML features the present commercial databases offer. Going forward with the XML- related technologies mentioned in this article, along with others such as Extensible Linking Language (X-Link) or XML Query Language (XQL), it’s a great advantage to any database


to have seamless access to its data in the form of XML documents. I know Microsoft’s SQL Server is full-speed ahead with this philosophy. As for DB2, there’s the DB2 XML Extender, which, at first blush, shows off a worthy list of features in regard to integrating XML with its database but is not available for the AS/400 platform. I would welcome any feedback from readers as to their experiences with products integrating XML with any particular database. In the meantime, download the example, get your feet wet with the technologies covered here, and soon you’ll be able to add XML processing to your technical skill toolbox.

REFERENCES AND RELATED MATERIALS

• DB2 XML Extender page: www-4.ibm.com/software/data/db2/extenders/ xmlext/index.html

• LotusXSL information page: http://alphaworks.ibm.com/aw.nsf/techmain/lotusxsl

• WebSphere XML programming page: www.iseries.ibm.com/products/websphere/ docs/as400v35/docs/xml.html

Figure 1: The code for this working example can be downloaded at www.midrangecomputing.com/mc.


Working_with_XML03-00.png 444x274

Method showing how to turn a ResultSet into XML format.

public String results2XML(ResultSet rs)
{

StringBuffer sb = new StringBuffer(
" ");
try
{

ResultSetMetaData rsMetaData = rs.getMetaData();
int fields = rsMetaData.getColumnCount();
while(rs.next())

{

catch(Exception e)
{
System.out.println(e);
}

sb.append("");
return sb.toString();

}

Snippet showing the Lotus XSL processor at work

. . .

StringReader xml = new StringReader(xmlSource);
FileInputStream xsl = new FileInputStream(xslSource);

XSLTProcessor proc = XSLTProcessorFactory.getProcessor();

proc.setStylesheetParam("sortMethod", "'" + request.getParameter("sort") + "'");
proc.setStylesheetParam("dataType", "'" + request.getParameter("dt") + "'");

proc.process(new XSLTInputSource(xml), new XSLTInputSource(xsl),
new XSLTResultTarget(response.getOutputStream()));
. . .

A

B

A

Figure 2: This is the code snippet of the downloadable example’s servlet.

a) XSL elements in an XSL stylesheet
. . .













. . .

Determining how to sort the XML document

sb.append(" ");
for (int i = 1; i <= fields; i++)
{
sb.append("<" + rsMetaData.getColumnName(i).toLowerCase() + ">" +
rs.getString(i).trim() +
" ");

}

sb.append(" ");
}

}












A

B

Figure 3: This is the code snippet of the downloadable example’s XSL stylesheet.


B

BLOG COMMENTS POWERED BY DISQUS