Transforming XML with XSLT
Problem
You need to make significant changes to the output format.
Solution
Use XSLT; it is fairly easy to use and does not require writing much Java.
Discussion
XSLT, or Extensible Style Language for Transformations, allows you a great deal of control over the output format. It can be used to change an XML file from one DTD into another, as might be needed in a business-to-business (B2B) application where information is passed from one industry-standard DTD to a site that uses another. It can also be used to render XML into another format such as HTML. Think of XSLT as a scripting language for transforming XML.
You need a set of classes called an XSLT
processor
. One
freely available XSLT processor is the
Apache project’s Xalan
(formerly available from Lotus/IBM as the Lotus XSL processor). To
use this, you create an XSL processor by calling the factory method
getProcessor( )
,
then call its parse method passing in two
XSLTInputSources
(one for the XML document and one for the XSL stylesheet) and one
XSLTResultTarget
for the output file.
Assume you have a file of people’s
names,
addresses, and so on, stored in an XML document such as the file
people.xml, shown in Example 21-1.
Example 21-1. people.xml
<?xml version="1.0"?>
<people>
<person>
<name>Ian Darwin</name>
<email>ian@darwinsys.com</email>
<country>Canada</country>
</person>
<person>
<name>Another Darwin</name>
<email type="intranet">ad</email>
<country>Canada</country>
</person>
</people>You ...