General discussion

Locked

techsite

By nitingautam ·
Tags: Off Topic
blog root

This conversation is currently closed to new comments.

1 total post (Page 1 of 1)  
| Thread display: Collapse - | Expand +

All Comments

Collapse -

Simplify XML programming with JDOM

by nitingautam In reply to techsite

<table border="0" cellpadding="0" cellspacing="0" width="100%"><tbody><tr valign="top"><td width="100%"><h1>Simplify XML programming with JDOM</h1><p id="subtitle"><em>This open-source API makes XML document manipulation easy for Java developers</em></p><img alt="" src="http://www.ibm.com/i/c.gif" class="display-img" height="6" width="1" /></td><td class="no-print" width="192"><a href="http://www.ibm.com/developerworks/"><img alt="developerWorks" src="http://www-128.ibm.com/developerworks/i/dw.gif" border="0" height="18" width="192" /></a></td></tr></tbody></table><table border="0" cellpadding="0" cellspacing="0" width="100%"><tbody><tr valign="top"><td width="10"><img alt="" src="http://www.ibm.com/i/c.gif" height="1" width="10" /></td><td width="100%"><table class="no-print" align="right" border="0" cellpadding="0" cellspacing="0" width="160"><tbody><tr><td width="10"><img alt="" src="http://www.ibm.com/i/c.gif" height="1" width="10" /></td><td><table border="0" cellpadding="0" cellspacing="0" width="150"><tbody><tr><td class="v14-header-1-small">Document options</td></tr></tbody></table><table class="v14-gray-table-border" border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="no-padding" width="150"><table border="0" cellpadding="0" cellspacing="0" width="143"><script language="JavaScript" type="text/javascript">
<!--
document.write('<tr valign="top"><td width="8"><img src="//www.ibm.com/i/c.gif" width="8" height="1" alt=""/></td><td width="16"><img alt="Set printer orientation to landscape mode" height="16" src="//www.ibm.com/i/v14/icons/printer.gif" width="16" vspace="3" /></td><td width="122"><p><b><a class="smallplainlink" href="javascript:print()">Print this page</a></b></p></td></tr>');
//-->
</script><tbody><tr valign="top"><td width="8"><img src="http://www.ibm.com/i/c.gif" alt="" height="1" width="8" /></td><td width="16"><img alt="Set printer orientation to landscape mode" src="http://www.ibm.com/i/v14/icons/printer.gif" height="16" vspace="3" width="16" /></td><td width="122"><p><b><a class="smallplainlink" href="javascript:print()">Print this page</a></b></p></td></tr>
<script language="JavaScript" type="text/javascript">
<!--
document.write('<tr valign="top"><td width="8"><img src="//www.ibm.com/i/c.gif" width="8" height="1" alt=""/></td><td width="16"><img src="//www.ibm.com/i/v14/icons/em.gif" height="16" width="16" vspace="3" alt="Email this page" /></td><td width="122"><p><a class="smallplainlink" href="javascript:void newWindow()"><b>E-mail this page</b></a></p></td></tr>');
//-->
</script><tr valign="top"><td width="8"><img src="http://www.ibm.com/i/c.gif" alt="" height="1" width="8" /></td><td width="16"><img src="http://www.ibm.com/i/v14/icons/em.gif" alt="Email this page" height="16" vspace="3" width="16" /></td><td width="122"><p><a class="smallplainlink" href="javascript:void newWindow()"><b>E-mail this page</b></a></p></td></tr><noscript><tr
valign="top"><td width="8"><img alt="" height="1" width="8"
src="//www.ibm.com/i/c.gif"/></td><td width="16"><img alt="" width="16"
height="16" src="//www.ibm.com/i/c.gif"/></td><td class="small"
width="122"><p><span class="ast">Document options requiring JavaScript
are not displayed</span></p></td></tr></noscript><tr valign="top"><td width="8"><img alt="" src="http://www.ibm.com/i/c.gif" height="1" width="8" /></td><td width="16"><img alt="" src="http://www.ibm.com/i/v14/icons/fw_bold.gif" border="0" height="16" vspace="3" width="16" /></td><td width="122"><p><a class="smallplainlink" href="http://www-106.ibm.com/developerworks/forums/dw_forum.jsp?forum=205&cat=10"><b>Discuss</b></a></p></td></tr></tbody></table></td></tr></tbody></table><!--start RESERVED FOR FUTURE USE INCLUDE FILES--><!-- 09/26/06 updated by gem -->

<br /><table border="0" cellpadding="0" cellspacing="0" width="150"><tbody><tr><td class="v14-header-2-small">Celebrate</td></tr></tbody></table><table class="v14-gray-table-border" border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="no-padding" width="150"><table border="0" cellpadding="0" cellspacing="0" width="143"><tbody><tr valign="top"><td width="8"><img src="http://www.ibm.com/i/c.gif" alt="" height="1" width="8" /></td><td><img src="http://www.ibm.com/i/v14/icons/fw_bold.gif" alt="" border="0" height="16" vspace="3" width="16" /></td><td width="125"><p><a href="http://www.alphaworks.ibm.com/anniversary" class="smallplainlink">Try the new alphaWorks services</a>
</p></td></tr></tbody></table></td></tr></tbody></table><!--end RESERVED FOR FUTURE USE INCLUDE FILES--><br /><table border="0" cellpadding="0" cellspacing="0" width="150"><tbody><tr><td class="v14-header-2-small">Rate this page</td></tr></tbody></table><table class="v14-gray-table-border" border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="no-padding" width="150"><table border="0" cellpadding="0" cellspacing="0" width="143"><tbody><tr valign="top"><td width="8"><img alt="" src="http://www.ibm.com/i/c.gif" height="1" width="8" /></td><td><img alt="" src="http://www.ibm.com/i/v14/icons/d_bold.gif" border="0" height="16" vspace="3" width="16" /></td><td width="125"><p><a href="http://www-128.ibm.com/developerworks/java/library/j-jdom/#rate" class="smallplainlink"><b>Help us improve this content</b></a></p></td></tr></tbody></table></td></tr></tbody></table><br /></td></tr></tbody></table><p>Level: Intermediate</p><p><a href="http://www-128.ibm.com/developerworks/java/library/j-jdom/#author">Wes Biggs</a> (<a href="mailto:wes@tralfamadore.com?subject=Simplify%20XML%20programming%20with%20JDOM">wes@tralfamadore.com</a>), Senior Developer, T.H.I.<br /><a href="http://www-128.ibm.com/developerworks/java/library/j-jdom/#author">Harry Evans</a> (<a href="mailto:harry@tralfamadore.com?subject=Simplify%20XML%20programming%20with%20JDOM">harry@tralfamadore.com</a>), Senior Developer, T.H.I.</p><p> 01 May 2001</p><blockquote>JDOM
is a unique Java toolkit for working with XML, engineered to enable
rapid development of XML applications. Its design embraces the Java
language from syntax to semantics. But is it better than existing --
and more standard -- XML APIs? Judge for yourself as we run through
some examples and illuminate the design goals of this popular
open-source project, which recently was formally accepted as a Java
Specification Request.</blockquote><!--start RESERVED FOR FUTURE USE INCLUDE FILES--><script language="JavaScript" type="text/javascript">
");
}
}
}
//-->
</script><div id="contents"><table border="0" cellpadding="0" cellspacing="0" width="75%"><tbody><tr valign="top"><td bgcolor="#f6f6f6" width="16"><img src="http://www.ibm.com/i/v14/icons/fw_bold.gif" alt="" border="0" height="16" vspace="3" width="16" /></td><td align="left" bgcolor="#f6f6f6" width="*"><p><a class="fbox" width="70%" href="http://www.ibm.com/developerworks/search/searchResults.jsp?source=google&searchType=1&searchSite=dW&searchScope=dW&query=Java+XML">More dW content related to: <b>Java XML</b></a></p></td><td bgcolor="#f6f6f6" width="3"><img src="http://www.ibm.com/i/c.gif" alt="" border="0" height="1" width="3" /></td></tr></tbody></table></div><!--end RESERVED FOR FUTURE USE INCLUDE FILES--><p>
As a developer, you've probably heard of the 80-20 rule, known in other
circles as Pareto's Law: a process or methodology will accommodate 80
percent of all possible situations, and the other 20 percent will need
to be handled on a case-by-case basis. The corollary for software
development is that it should be extremely easy for developers to
accomplish 80 percent of the things they could possibly do with a given
technology.</p><p>
Of course, software products and standards don't always evolve
according to the 80-20 rule. The fractured space of Java XML tools, in
particular, illustrates an exception to that rule. The Java programming
world is full of APIs -- some homegrown, some backed by the marketing
might of
a major corporation -- that provide sophisticated solutions to
particular XML tasks. As testament to the universality of XML, for
every new task, there is a new technology. But what's the glue, and how
do you go about finding the right tool for the 80 percent of things
that you have to do over and over -- basic XML tree manipulation with
an intuitive mapping to the Java language? JDOM is an XML API built
with exactly that question in mind.
</p><p><a name="h1">Tag, you're it: Java and XML</a></p><p>In
many ways, the Java language has become the programming language of
choice for XML. With groundbreaking work from the Apache Software
Foundation and IBM alphaWorks, there are now complete tool chains for
creating, manipulating, transforming, and parsing XML documents.
</p><p>But while many Java developers use XML daily, Sun has lagged
behind the industry in incorporating XML into the Java platform.
Because the Java 2 platform went gold before XML had made its mark as a
key technology for everything from business-to-business integration to
Web site content streamlining, Sun has been using the JSR process to
grandfather in existing XML APIs that have gained wide acceptability.
The most significant addition to date has been the inclusion of JAXP,
the Java API for XML Parsing, which includes three packages: </p><ul><li>
<code>org.w3c.dom</code>, the Java implementation of the W3C's recommendation for a standard programmatic Document Object Model for XML</li><li>
<code>org.xml.sax</code>, the event-driven Simple API for XML parsing</li><li>
<code>javax.xml.parsers</code>, a factory implementation that allows application developers to configure and obtain a particular parser implementation</li></ul><p>
Though the inclusion of these packages is a good thing for Java
developers, it merely represents a formal nod to existing API
standards, and not a giant leap forward in providing elegant Java-XML
interoperability. What the core Java platform has lacked is an
intuitive interface for manipulating XML documents as Java objects.
</p><p>Enter JDOM. The brainchild of two well-known Java developers
and authors, Brett McLaughlin and Jason Hunter, JDOM was inaugurated as
an open-source project under an Apache-like license in early 2000. It
has grown to include contributions and incorporate feedback and bug
fixes from a wide base of Java developers, and aims to build a complete
Java platform-based solution for accessing, manipulating, and
outputting XML data from Java code.
</p><br /><table border="0" cellpadding="0" cellspacing="0" width="100%"><tbody><tr><td><img src="http://www.ibm.com/i/v14/rules/blue_rule.gif" alt="" height="1" width="100%" /></td></tr></tbody></table><table class="no-print" align="right" cellpadding="0" cellspacing="0"><tbody><tr align="right"><td><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td valign="middle"><img src="http://www.ibm.com/i/v14/icons/u_bold.gif" alt="" border="0" height="16" width="16" /><br /></td><td align="right" valign="top"><a href="http://www-128.ibm.com/developerworks/java/library/j-jdom/#main" class="fbox"><b>Back to top</b></a></td></tr></tbody></table></td></tr></tbody></table><br /><br /><p><a name="h2">It's the API, dummy: Where JDOM fits</a></p><p>

JDOM can be used as an alternative to the <code>org.w3c.dom</code>
package for programmatically manipulating XML documents. It's not a
drop-in replacement, and, in fact, JDOM and DOM can happily coexist. In
addition, JDOM is not concerned with parsing XML from text input,
although it provides wrapper classes that take much of the work out of
configuring and running a parser implementation. JDOM builds on the
strengths of existing APIs to build, as the project home page states,
"a better mousetrap."
</p><p>
To understand why there is a need for an alternative API, consider the design constraints of the W3C DOM:
</p><ul><li>
<b>Language independent.</b> The DOM wasn't designed with the Java
language in mind. While this approach keeps a very similar API between
different languages, it also makes the API more cumbersome for
programmers who are used to the Java language's idioms. For example,
while the Java language has a <code>String</code> class built into the language, the DOM specification defines its own <code>Text</code> class.<br />
</li><li>
<b>Strict hierarchies.</b> The DOM's API follows directly from the XML specification itself. In XML, everything's a node, so you find a <code>Node</code>-based interface in the DOM that almost everything extends and a host of methods that return <code>Node</code>.
It's elegant from a polymorphism point of view, but as explained above,
it's difficult and cumbersome to work with in the Java language, where
explicit downcasts from <code>Node</code> to the leaf types lead to long-winded and less understandable code.<br />
</li><li>
<b>Interface driven.</b> The public DOM API consists of interfaces only (the one exception, appropriately enough, is an <code>Exception</code>
class). The W3C isn't interested in providing implementations, just in
defining interfaces, which makes sense. But it also means that using
the API as a Java programmer imposes a degree of separation when
creating XML objects, as the W3C standards make heavy use of generic
factory classes and similar flexible but less direct patterns. For
certain uses where XML documents are built only by a parser, and never
by application-level code, this is irrelevant. But as XML use becomes
more widespread, not all problems continue to look so parser-driven,
and application developers need a convenient way to construct XML
objects programmatically.</li></ul><p>
To the programmer, these constraints mean a heavy (both in terms of
memory use and interface size) and unwieldy API that can be hard to
learn and frustrating to use. In contrast, JDOM was formulated as a
lightweight API that, first and foremost, is Java-centric. It does away
with the above awkwardness by turning the DOM's principles on their
head:
</p><ul><li>
<b>JDOM is Java platform specific.</b> The API uses the Java language's built-in <code>String</code> support wherever possible, so that text values are always available as <code>String</code>s. It
also makes use of the Java 2 platform collection classes, like <code>List</code> and <code>Iterator</code>, providing a rich environment for programmers familiar with the Java language.
<br />
</li><li>
<b>No hierarchies.</b> In JDOM, an XML element is an instance of <code>Element</code>, an XML attribute is an instance of <code>Attribute</code>, and an XML document itself is an instance of <code>Document</code>.
Because all of these represent different concepts in XML, they are
always referenced as their own types, never as an amorphous "node."<br />
</li><li>
<b>Class driven.</b> Because JDOM objects are direct instances of classes like <code>Document</code>, <code>Element</code>, and <code>Attribute</code>, creating one is as easy as using the <code>new</code>
operator in the Java language. It also means that there are no factory
interfaces to configure -- JDOM is ready to use straight out of the jar.</li></ul><br /><table border="0" cellpadding="0" cellspacing="0" width="100%"><tbody><tr><td><img src="http://www.ibm.com/i/v14/rules/blue_rule.gif" alt="" height="1" width="100%" /></td></tr></tbody></table><table class="no-print" align="right" cellpadding="0" cellspacing="0"><tbody><tr align="right"><td><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td valign="middle"><img src="http://www.ibm.com/i/v14/icons/u_bold.gif" alt="" border="0" height="16" width="16" /><br /></td><td align="right" valign="top"><a href="http://www-128.ibm.com/developerworks/java/library/j-jdom/#main" class="fbox"><b>Back to top</b></a></td></tr></tbody></table></td></tr></tbody></table><br /><br /><p><a name="h3">Look ma, no Nodes: Building and manipulating JDOM documents</a></p><p>

JDOM makes use of standard Java coding patterns. Where possible, it uses the Java <code>new</code>
operator instead of complex factory patterns, making object
manipulation easy, even for the novice user. For example, let's look at
how you would build a simple XML document from scratch using JDOM. The
structure we are going to build is shown in Listing 1. (Download the
complete code for this article from <a href="http://www-128.ibm.com/developerworks/java/library/j-jdom/#resources">Resources</a>.) </p><br /><a name="code1"><b>Listing 1. Sample XML document to build</b></a><br /><table bgcolor="#eeeeee" border="1" cellpadding="5" cellspacing="0" width="100%"><tbody><tr><td><pre><code class="section">

<?xml version="1.0" encoding="UTF-8"?>
<car vin="123fhg5869705iop90">
<!--Description of a car-->
<make>Toyota</make>
<model>Celica</model>
<year>1997</year>
<color>green</color>
<license state="CA">1ABC234</license>
</car>
</code></pre></td></tr></tbody></table><br /><p>
Note: We'll build <a href="http://www-128.ibm.com/developerworks/java/library/j-jdom/code.html" target="_new">the sample document</a> detailed in Listings 2 through 7 below.</p><p>To begin, let's create the root element and add it to a document:</p><br /><a name="code2"><b>Listing 2. Creating a Document
</b></a><br /><table bgcolor="#eeeeee" border="1" cellpadding="5" cellspacing="0" width="100%"><tbody><tr><td><pre><code class="section">

Element carElement = new Element("car");
Document myDocument = new Document(carElement);
</code></pre></td></tr></tbody></table><br /><p>
This step creates a new <code>org.jdom.Element</code> and makes it the root element of the <code>org.jdom.Document</code>
<code>myDocument</code>. (If you're using the sample code provided in <a href="http://www-128.ibm.com/developerworks/java/library/j-jdom/#resources">Resources</a>, make sure to import <code>org.jdom.*</code>.) Because an XML document must always have a single root element, <code>Document</code> takes the <code>Element</code> in its constructor. </p><p>Next, we'll add the <code>vin</code> attribute:</p><br /><a name="code3"><b>Listing 3. Adding an Attribute
</b></a><br /><table bgcolor="#eeeeee" border="1" cellpadding="5" cellspacing="0" width="100%"><tbody><tr><td><pre><code class="section">

carElement.addAttribute(new Attribute("vin", "123fhg5869705iop90"));
</code></pre></td></tr></tbody></table><br /><p>
Adding elements is also very straightforward. Here we add the <code>make</code> element:
</p><br /><a name="code4"><b>Listing 4. Elements and sub-elements</b></a><br /><table bgcolor="#eeeeee" border="1" cellpadding="5" cellspacing="0" width="100%"><tbody><tr><td><pre><code class="section">

Element make = new Element("make");
make.addContent("Toyota");
carElement.addContent(make);
</code></pre></td></tr></tbody></table><br /><p>
Because the <code>addContent</code> method of <code>Element</code> returns the <code>Element</code>, we could also write this as:
</p><br /><a name="code5"><b>Listing 5. Adding elements in a terse form</b></a><br /><table bgcolor="#eeeeee" border="1" cellpadding="5" cellspacing="0" width="100%"><tbody><tr><td><pre><code class="section">

carElement.addContent(new Element("make").addContent("Toyota"));
</code></pre></td></tr></tbody></table><br /><p>
Both of these statements accomplish the same thing. Some would argue that
the first example is more readable, but the second becomes more
readable if you are constructing many elements at once. To finish
constructing the document:
</p><br /><a name="code6"><b>Listing 6. Adding the remaining elements</b></a><br /><table bgcolor="#eeeeee" border="1" cellpadding="5" cellspacing="0" width="100%"><tbody><tr><td><pre><code class="section">

carElement.addContent(new Element("model").addContent("Celica"));
carElement.addContent(new Element("year").addContent("1997"));
carElement.addContent(new Element("color").addContent("green"));
carElement.addContent(new Element("license")
.addContent("1ABC234").addAttribute("state", "CA"));
</code></pre></td></tr></tbody></table><br /><p>
You will notice that for the <code>license</code> element, we not only added the
content of the element, we also added an attribute to it, specifying the
state in which the license was issued. This is possible because the
<code>addContent</code> methods on <code>Element</code> always return the <code>Element</code> itself, instead of having a void declaration.
</p><p>
Adding a comment section or other standard XML types is done the same way:
</p><br /><a name="code7"><b>Listing 7. Adding a comment</b></a><br /><table bgcolor="#eeeeee" border="1" cellpadding="5" cellspacing="0" width="100%"><tbody><tr><td><pre><code class="section">

carElement.addContent(new Comment("Description of a car"));
</code></pre></td></tr></tbody></table><br /><p>
Manipulation of the document takes place in a similar fashion. For
example, to obtain a reference to the <code>year</code> element, we use the <code>getChild</code> method of <code>Element</code>:
</p><br /><a name="code8"><b>Listing 8. Accessing child elements</b></a><br /><table bgcolor="#eeeeee" border="1" cellpadding="5" cellspacing="0" width="100%"><tbody><tr><td><pre><code class="section">

Element yearElement = carElement.getChild("year");
</code></pre></td></tr></tbody></table><br /><p>
This statement actually will return the first child <code>Element</code> with the element
name <code>year</code>. If there is no <code>year</code> element, then the call will return
null. Note that we didn't need to upcast the return value from anything like the DOM <code>Node</code> interface -- children of <code>Element</code>s are simply <code>Element</code>s. In a similar fashion, we can remove the <code>year</code> element from the document:
</p><br /><a name="code9"><b>Listing 9. Removing child elements</b></a><br /><table bgcolor="#eeeeee" border="1" cellpadding="5" cellspacing="0" width="100%"><tbody><tr><td><pre><code class="section">

boolean removed = carElement.removeChild("year");
</code></pre></td></tr></tbody></table><br /><p>
This call will remove the <code>year</code> element only; the rest of the document
remains unchanged.
</p><p>
So far, we have covered how documents can be created and manipulated.
To output our finished document to the console we can use JDOM's <code>XMLOutputter</code> class:
</p><br /><a name="code10"><b>Listing 10. Turning JDOM into XML text</b></a><br /><table bgcolor="#eeeeee" border="1" cellpadding="5" cellspacing="0" width="100%"><tbody><tr><td><pre><code class="section">

try {
XMLOutputter outputter = new XMLOutputter(" ", true);
outputter.output(myDocument, System.out);
} catch (java.io.IOException e) {
e.printStackTrace();
}
</code></pre></td></tr></tbody></table><br /><p>
<code>XMLOutputter</code> has a few formatting options. Here we've specified that we
want child elements indented two spaces from the parent element, and that
we want new lines between elements. <code>XMLOutputter</code> can output to either
a <code>Writer</code> or an <code>OutputStream</code>. To output to a file we could simply
change the output line to:
</p><br /><a name="code11"><b>Listing 11. Using a FileWriter to output XML</b></a><br /><table bgcolor="#eeeeee" border="1" cellpadding="5" cellspacing="0" width="100%"><tbody><tr><td><pre><code class="section">

FileWriter writer = new FileWriter("/some/directory/myFile.xml");
outputter.output(myDocument, writer);
writer.close();
</code></pre></td></tr></tbody></table><br /><br /><table border="0" cellpadding="0" cellspacing="0" width="100%"><tbody><tr><td><img src="http://www.ibm.com/i/v14/rules/blue_rule.gif" alt="" height="1" width="100%" /></td></tr></tbody></table><table class="no-print" align="right" cellpadding="0" cellspacing="0"><tbody><tr align="right"><td><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td valign="middle"><img src="http://www.ibm.com/i/v14/icons/u_bold.gif" alt="" border="0" height="16" width="16" /><br /></td><td align="right" valign="top"><a href="http://www-128.ibm.com/developerworks/java/library/j-jdom/#main" class="fbox"><b>Back to top</b></a></td></tr></tbody></table></td></tr></tbody></table><br /><br /><p><a name="h3">Plays well with others: Interoperating with existing XML tools</a></p><p>

One of the interesting features of JDOM is its interoperability with
other APIs. Using JDOM, you can output a document not only to a <code>Stream</code> or a <code>Reader</code>, but also as a SAX <code>Event Stream</code> or as a DOM <code>Document</code>.
This flexibility allows JDOM to be used in a heterogeneous environment
or to be added to systems already using another method for handling
XML. As we'll see in a later example, it also allows JDOM to use other
XML tools that don't yet recognize the JDOM data structures natively.
</p><p>
Another use of JDOM is the ability to read and manipulate XML data that
already exists. Reading a well-formed XML file is done by using one of the
classes in <code>org.jdom.input</code>. In this example, we'll use <code>SAXBuilder</code>:
</p><br /><a name="code12"><b>Listing 12. Parsing an XML file with SAXBuilder
</b></a><br /><table bgcolor="#eeeeee" border="1" cellpadding="5" cellspacing="0" width="100%"><tbody><tr><td><pre><code class="section">

try {
SAXBuilder builder = new SAXBuilder();
Document anotherDocument =
builder.build(new File("/some/directory/sample.xml"));
} catch(JDOMException e) {
e.printStackTrace();
} catch(NullPointerException e) {
e.printStackTrace();
}
</code></pre></td></tr></tbody></table><br /><p>
You can manipulate the document built through this process in the same ways shown back in Listings 2 through 7.</p><p>
Another practical application of JDOM combines it with the Xalan product from Apache (see <a href="http://www-128.ibm.com/developerworks/java/library/j-jdom/#resources">Resources</a&gt.
Using the car example above, we will construct a Web page for an online
car dealer presenting the details of a particular car. First, we will
assume that the document we built above represents the information
about the car we are going to present
to the user. Next, we will combine this JDOM <code>Document</code> with an XSL stylesheet and output the HTML-formatted results to a servlet's <code>OutputStream</code> for display in the user's browser.
</p><p>
In this case, the XSL stylesheet we are going to use is called <code>car.xsl</code>:
</p><br /><a name="code13"><b>Listing 13. XSL document for transforming car records to HTML</b></a><br /><table bgcolor="#eeeeee" border="1" cellpadding="5" cellspacing="0" width="100%"><tbody><tr><td><pre><code class="section">

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

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/car">
<html>
<head>
<title><xsl:value-of select="make"/> <xsl:value-of select="model"/>
</head>
<body>
<h1><xsl:value-of select="make"/></h1><br />
<h2><xsl:value-of select="model"/></h2><br />
<table border="0">
<tr><td>VIN:</td><td><xsl:value-of select="@vin"/></td></tr>
<tr><td>Year:</td><td><xsl:value-of select="year"/></td></tr>
<tr><td>Color:</td><td><xsl:value-of select="color"/></td></tr>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
</code></pre></td></tr></tbody></table><br /><p>
Now we will turn the <code>org.jdom.Document</code> into a DOM <code>Document</code> and feed it to Xalan, along with the file that represents our XSL and the <code>OutputStream</code> that
we obtained from our hypothetical application server, which happens to be using servlets (shown in Listing 14).
</p><br /><a name="code14"><b>Listing 14. Creating an HTML document with JDOM and Xalan</b></a><br /><table bgcolor="#eeeeee" border="1" cellpadding="5" cellspacing="0" width="100%"><tbody><tr><td><pre><code class="section">

TransformerFactory tFactory = TransformerFactory.newInstance();

// Make the input sources for the XML and XSLT documents
org.jdom.output.DOMOutputter outputter = new org.jdom.output.DOMOutputter();
org.w3c.dom.Document domDocument = outputter.output(myDocument);
javax.xml.transform.Source xmlSource =
new javax.xml.transform.dom.DOMSource(domDocument);
StreamSource xsltSource =
new StreamSource(new FileInputStream("/some/directory/car.xsl"));

// Make the output result for the finished document using
// the HTTPResponse OutputStream
StreamResult xmlResult = new StreamResult(response.getOutputStream());

// Get a XSLT transformer
Transformer transformer = tFactory.newTransformer(xsltSource);

// Do the transform
transformer.transform(xmlSource, xmlResult);
</code></pre></td></tr></tbody></table><br /><p>
In this example, the output is streamed through the <code>HTTPResponse</code>
<code>OutputStream</code> of a Java servlet. However, the stream could just as easily be a filestream as in our earlier example with <code>XMLOutputter</code>. We used <code>DOMOutputter</code> to generate the XML source for Xalan. However, we could generate the same input by using <code>XMLOutputter</code> to output our XML document as a <code>String</code> and then make it into a <code>StreamSource</code>. Talk about flexibility: JDOM can output its structure as a <code>String</code>, a SAX <code>Event Stream</code>, or a DOM <code>Document</code>.
This allows JDOM to interface with tools that can take any of these
models as input. (For additional functionality, check the JDOM Web site
for the <code>contrib</code> package, where you'll find a worthy
library of JDOM-based utilities that provide tools like a JDBC
ResultSet-based builder, XPATH implementation, and more.)
</p><p>In just a few lines of code, JDOM enables a wide variety of
functionality. We have parsed and programatically created XML documents
in XML, manipulated those documents, and used them to produce an XML-
driven Web page.
</p><table align="right" border="0" cellpadding="0" cellspacing="0" width="40%"><tbody><tr><td width="10"><img alt="" src="http://www.ibm.com/i/c.gif" height="1" width="10" /></td><td><table border="1" cellpadding="5" cellspacing="0" width="100%"><tbody><tr><td bgcolor="#eeeeee">
<a name="sidebar"><b>Sun and JDOM: What's in a name?</b></a><br />
The official 1.0 release of JDOM may coincide with
its continuing evolution in the Java Community Process. Submitted as
JSR-102, JDOM has been approved for eventual inclusion in the core
Java platform, with this comment from Sun: "JDOM does appear to be
significantly easier to use than the earlier APIs, so we believe it
will be a useful addition to the platform." According to the JSR, a
1.0 release might see JDOM's packaging change from "org.jdom" to
"javax.xml.tree". While the future certainly looks positive,
developers may eventually have to retrofit their code to work with the
new version.
</td></tr></tbody></table></td></tr></tbody></table><br /><table border="0" cellpadding="0" cellspacing="0" width="100%"><tbody><tr><td><img src="http://www.ibm.com/i/v14/rules/blue_rule.gif" alt="" height="1" width="100%" /></td></tr></tbody></table><table class="no-print" align="right" cellpadding="0" cellspacing="0"><tbody><tr align="right"><td><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td valign="middle"><img src="http://www.ibm.com/i/v14/icons/u_bold.gif" alt="" border="0" height="16" width="16" /><br /></td><td align="right" valign="top"><a href="http://www-128.ibm.com/developerworks/java/library/j-jdom/#main" class="fbox"><b>Back to top</b></a></td></tr></tbody></table></td></tr></tbody></table><br /><br /><p><a name="h5">JDOM grows up: A glimpse of the future</a></p><p>
As of this writing, the JDOM project has released its Beta 6 version.
Even with its beta status, JDOM has proved to be a stable
implementation for many real-world implementations. While
much of the API is solid, work continues in a number of areas that will
potentially impact the existing interfaces. Therefore, any development
projects undertaken at this point need not shirk JDOM for fear of a
buggy implementation, but should consider the fact that certain method
signatures or specific semantics are still likely to change before
final release and potential adoption into the core Java API. (See <a href="http://www-128.ibm.com/developerworks/java/library/j-jdom/#sidebar">What's in a name?</a&gt
</p><p>
The near-term to-do list for JDOM is focused on stabilizing the API and
evaluating the performance aspects of parts of the implementation.
Other items that are in progress but that could hinder some application
developers include support for DTD entities and other less frequent
constructs. Further down the road is core support for XPATH, the XML
path language native to applications like XSLT, and more direct
integration with XML data sources.
</p><p>So, in conclusion, is JDOM better than existing XML APIs? If
you dream in Java, the answer is probably yes. JDOM isn't meant to
supercede your favorite parser or XML-aware database, but its design
principles make for a particularly rapid learning curve for Java
developers entering or well on their way to ruling the XML world.
</p><br /><table border="0" cellpadding="0" cellspacing="0" width="100%"><tbody><tr><td><img src="http://www.ibm.com/i/v14/rules/blue_rule.gif" alt="" height="1" width="100%" /></td></tr></tbody></table><table class="no-print" align="right" cellpadding="0" cellspacing="0"><tbody><tr align="right"><td><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td valign="middle"><img src="http://www.ibm.com/i/v14/icons/u_bold.gif" alt="" border="0" height="16" width="16" /><br /></td><td align="right" valign="top"><a href="http://www-128.ibm.com/developerworks/java/library/j-jdom/#main" class="fbox"><b>Back to top</b></a></td></tr></tbody></table></td></tr></tbody></table><br /><br /><p><a name="resources">Resources</a></p><ul><li><a href="http://www-106.ibm.com/developerworks/forums/dw_forum.jsp?forum=205&cat=10">Participate in the discussion forum</a>.<br /></li><li>Download the <a href="http://www-128.ibm.com/developerworks/java/library/j-jdom/jdomExamples.jar">sample code</a>
(source and compiled versions of a Java class that includes all the
example code and the XML and XSL files used in this article). You will
need JDOM, Xerces, and Xalan in your classpath to run the code.<br />
<br />
<br /></li><li>For the latest release of JDOM, online API documentation and more, check out the <a href="http://www.jdom.org/">JDOM Web site</a>.<br />
<br />
<br /></li><li>For more information about Xalan, Xerces, and other Java XML products, check out the <a href="http://xml.apache.org/">Apache XML site</a>.<br />
<br />
<br /></li><li>Visit the <a href="http://www.xml.com/">XML Web site</a> for general XML information, tutorials, and resources. <br />
<br />
<br /></li><li>And don't forget the developerWorks <a href="http://www.ibm.com/developerworks/xml/">XML zone</a> for a wealth of XML-related content.<br />
<br />
<br /></li><li>IBM's alphaWorks site offers several tools for Java and XML developers:
<ul><li>
<a href="http://xerces.apache.org/xerces2-j/">Apache's Xerces-J Parser</a>
introduces the Xerces Native Interface (XNI), a complete framework for
building parser components and configurations that is extremely modular
and easy to program.</li><li>To diagnose improper use of the XML Schema language, try <a href="http://alphaworks.ibm.com/tech/xmlsqc/">XML Schema Quality Checker</a>.</li><li>The <a href="http://alphaworks.ibm.com/tech/xmlsecuritysuite/">XML Security Suite</a> offers a variety of security features such as digital signature, element-wise encryption, and access control.</li></ul>
<br />
</li><li>JDOM's creators are both well-known authors. We recommend you read Jason Hunter's <a href="http://www.amazon.com/gp/product/0596000405/qid=988411810/sr=2-1/103-4008905-9647037?n=283155">
<i>Java Servlet Programming, 2nd Edition</i>
</a> (O'Reilly, April 2001) and Brett McLaughlin's <a href="http://www.amazon.com/gp/product/0596000162/qid=988412025/sr=1-1/ref=sc_b_2/103-4008905-9647037?n=283155">
<i>Java and XML</i>
</a> (O'Reilly, June 2000).<br />
<br />
<br /></li><li>In addition, Brett's written several related articles for developerWorks:
<ul><li>"<a href="http://www.ibm.com/developerworks/java/library/x-tipcdm.html">Converting from DOM</a>" (April 2001)</li><li>"<a href="http://www.ibm.com/developerworks/java/library/x-tipcsx.html">Converting from SAX</a>" (April 2001)</li><li>"<a href="http://www.ibm.com/developerworks/java/library/x-tipjdom.html">Using JDOM and XSLT</a>" (March 2001)</li><li>"<a href="http://www.ibm.com/developerworks/java/library/x-jaxp/">All about JAXP</a>" (November 2000)</li><li>"<a href="http://www.ibm.com/developerworks/java/library/x-jaxp1.html">JAXP revisited</a>" (December 2000)</li></ul>
<br />
</li><li>Join the developerWorks <a href="news://news.software.ibm.com/ibm.software.developerworks.xml.javatools">XML tools and APIs discussion</a> for Java developers. <br />
<br />
<br /></li><li>Here's more information on <a href="http://www-4.ibm.com/software/webservers/appserv/doc/v35/ae/infocenter/was/04020306.html">using DOM to incorporate XML documents into applications</a>.</li></ul></td></tr></tbody></table>

Back to After Hours Forum
1 total post (Page 1 of 1)  

Related Discussions

Related Forums