24
Sun, Nov
1 New Articles

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

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: