|By Shari Jones||
|August 17, 2001 12:00 AM EDT||
This second of a two-part series on JDOM examines in greater detail what it takes to use JDOM to perform some common tasks. In particular, I'll illustrate how to create JDOM documents, read JDOM documents from various sources (including SAX and DOM), output to various sources, and how to use JDOM with XSLT.
The overview of JDOM discussed in Part 1 (XML-J, Vol. 2, issue 7) revealed that JDOM bridges the gap between inconsistencies in DOM parser APIs via adapters. It also takes SAX and DOM to the next level in terms of ease of use, by compensating for the weaknesses of these APIs when it comes to XML document manipulation.
Part 1 explored the JDOM API and the packages and classes that are most significant for developing in JDOM. The main components of a JDOM document that were defined in Part 1 are critical prerequisites for understanding this article.
Creating a JDOM Document
JDOM documents can be created in two ways - from scratch or from some other input source, such as an XML document, a series of SAX events, or a DOM document. First, we'll discuss how to create a JDOM document in memory from scratch, and then, in the next section, we'll address how to output that document in various different formats.
After we create a JDOM document and show how to output its content, we will demonstrate how to input an existing XML document, a series of SAX events, or a DOM document, and convert it into a JDOM document, which is the second option for creating a JDOM document.
Creating a JDOM Document in Memory
Let's begin by creating a JDOM document in memory, from scratch. Since JDOM was written with the Java developer in mind (keeping as close to Java standards as possible), creating a new JDOM document in memory is straightforward for Java developers.
To create a JDOM document in memory using the core JDOM classes, Document and Element from the org.jdom package, use the following code:
Document doc = new Document( new
.setText("Hello World!") );
This creates, in memory, a bare bones JDOM document and stores it in the variable doc. That's all there is to it. Next, we'll look at outputting this document to the screen, so we can see what it looks like in XML.
Outputting JDOM Documents
After creating a JDOM document, it can be output using one of three primary ways:
1. org.jdom.output.DOMOutputter: As a DOM document
2. org.jdom.output.SAXOutputter: As a sequence of SAX events
3. org.jdom.output.XMLOutputter: As an XML document to a file or an output stream
As part of the org.jdom.output package, XMLOutputter outputs a JDOM document to an output stream, such as the screen, or to a file. Alternatively, the SAXOutputter or DOMOutputter classes, also of the org.jdom.output package, can be used to output the JDOM document as a series of SAX events or as a DOM document, respectively.
In Listing 1, we illustrate output using XMLOutputter to output to the standard output stream, System.out, which by default is the screen when running in a DOS/UNIX command window.
When a JDOM document is output as an XML document, it's output as one or two long lines of XML code unless you specify otherwise. This is fine if it's being sent to another application or system for processing, and is actually the most compact. However, it makes it very difficult to read and see the structure.
To format the XML output to improve readability - by humans, not computers - we can specify a couple of parameters when creating the XMLOutputter. The first parameter defines the level of indentation - usually as a sequence of spaces - and the second is a Boolean value that, if set to true, causes new lines to be added to the output.
Here's an example:
outputter = new XMLOutputter(" ",
We use this approach in our HelloWorld example shown later in the article.
Note that since XMLOutputter contains methods to output a JDOM document to a java.io.OutputStream as well as to a java.io.Writer, you can use the same approach whether outputting to a file, an output stream (such as across a network), to the screen, or to any other form of Writer or OutputStream.
Other output methods in XMLOutputter allow you to output just parts of the JDOM document such as CDATA sections, comments, elements, entities, and processing instructions. We talked about each of these components in Part 1.
The JDOM document created as described in the last example will be output to the screen. The code required is in Listing 1.
To compile this file, first ensure that you have set up your Java environment correctly for use with JDOM. Your CLASSPATH must include the xerces.jar file found in the lib subdirectory of your JDOM distribution. The xerces.jar file should be followed in the CLASSPATH by the jdom.jar file from the build subdirectory of your JDOM distribution.
Next, to compile the HelloWorld.java file, type the following code:
After the HelloWorld.java file compiles, run the HelloWorld application using:
This produces the following output:
<?xml version="1.0" encoding="UTF-8"?> <root-element>Hello World!</root-element>
The root-element tag is from the code defined in the HelloWorld.java file, specifically from the line that instantiates a new Element. Here is the code that defines the name of the new Element.
The text "Hello World!" also was defined in the code in the HelloWorld.java file and by the call to the setText method. The following code defines the text for the root element:
new Element("root-element").setText("Hello World!")
As you can see, using JDOM, it's possible to produce perfectly valid XML output with little prior knowledge of XML. This was one of the original goals of JDOM.
Outputting Using DOMOutputter
We just saw how to output a JDOM document as an XML file. Using DOMOutputter, we can output a JDOM document as a DOM document. This is useful when interfacing with another application or system that expects a DOM document as its input.
The following lines of code show how to create and use DOMOutputter to output a JDOM document, doc.
DOMOutputter outputter = new DOMOutputter(); outputter.output( doc );
In addition to outputting JDOM documents, DOMOutputter also provides methods that allow you to output JDOM elements and attributes. See the JDOM API documentation for details.
Outputting Using SAXOutputter
We just saw how to output a JDOM document as an XML file and as a DOM document. The final way to output a JDOM document is as a sequence of SAX events. This is useful for interfacing with applications or components that handle a series of SAX events.
When constructing a SAXOutputter, you must specify a SAX content handler (actually an org.xml.sax.ContentHandler) as a minimum. You then have the option of specifying a SAX error handler (org.xml.sax.ErrorHandler), DTD handler (org.xml.sax.DTDHandler), and entity handler (org.xml.sax.EntityHandler) after you have created the SAXOutputter object.
The following lines of code show how to create and use SAXOutputter to output a JDOM document, doc.
SAXOutputter outputter = new SAXOutputter( contentHandler ); outputter.output( doc );
After creating a SAXOutputter object, you need to invoke the output() method to pass the JDOM document object you want to output to the outputter.
Inputting to JDOM Documents
Earlier in this article we saw how to create a JDOM document from scratch. Another way of creating a JDOM document is to read an XML document or input stream (using a SAX parser), or input a DOM document. Again, we will use an output stream to output the JDOM document.
To input an XML file, input stream, or DOM document as a JDOM document, use the SAXBuilder or DOMBuilder classes, respectively, from the org.jdom.input package.
Inputting Using SAXBuilder
Perhaps the most common means of building a JDOM document is to use SAXBuilder. SAXBuilder uses a SAX parser to parse an XML input file or input stream. Building a JDOM document using SAXBuilder is a two-step process.
In step one, you need to create a new instance of a SAXBuilder object. Next, invoke one of the build methods for reading the XML input and building a JDOM document object.
Four different constructors are available for creating a new SAXBuilder object, the primary one using the default SAX parser as determined by JAXP. Validation is turned off. It can be enabled and disabled after the construction of a SAXBuilder object by using the setValidation() method.
The other three constructors allow more control over whether or not validation is enabled or disabled and in choosing an alternate SAX parser.
After creating a SAXBuilder object, other methods are available that allow us to initialize it with a custom DTD handler, Entity resolver, XML filter, and error handler.
Once we have instantiated a new SAXBuilder object, we can use it to build a JDOM document. There are seven different publicly accessible build methods available.
The main differences between the seven build methods lie in where the XML input is to come from. It can come from a variety of sources, including one specified by a java.io.File, java.io.InputStream, java.io.Reader, a URI specified as a java.lang.String, or a java.net.URL.
SAX parsers tend to be the first choice over DOM parsers because of their speed when reading in XML and generating a JDOM document. If you prefer not to use the default SAX parser with SAXBuilder, you can always substitute a third-party SAX parser.
Simply pass the name of the SAX Driver class to the SAXBuilder constructor when creating the builder. Make sure that the classes required by the alternate parser are available in your CLASSPATH. SAXBuilder will then use the specified SAX parser to build a JDOM document.
Inputting Using DOMBuilder
An alternative to the SAXBuilder is the DOMBuilder. The DOMBuilder class is intended to allow us to build a JDOM document from a preexisting DOM document. It uses basically the same steps as when using SAXBuilder.
First, create a new instance of a DOMBuilder object. Next, invoke one of the build methods to read the XML input and build a JDOM document object.
To create a new DOMBuilder object, four different constructors are available. The default constructor creates a new DOMBuilder using the default DOM parser - as specified by the default JAXP parser, or a JDOM default if not. Validation is turned off.
The default constructor with no validation suffices for most purposes, but the other three constructors allow for greater control when selecting a DOM parser. They also allow you to enable or disable validation.
After creating a DOMBuilder object, use one of the DOMBuilder.build methods to build a JDOM document from an existing DOM document object. This build method is just like the SAXBuilder.build methods except that it takes an org.w3c.dom.Document object as a single argument for its input.
In addition, DOMBuilder contains a build method that allows you to construct a JDOM element object directly from a DOM element (org.w3c.dom.Element) object. The DOMBuilder class is intended primarily as a way of generating a JDOM document from a preexisting DOM document.
The DOMBuilder class contains three additional DOMBuilder.build methods, each of these taking a single argument - either a java.io.File, java.io.InputStream, or a java.net.URL - and building a JDOM document from a file, input stream, or URL, respectively. These other methods are provided as a means of cross-checking the SAXBuilder.build methods, which is the recommended parser for XML parsing.
Generating a JDOM document using a DOM parser is slow, hence the SAX parser recommendation. The only possible exception to not using a SAX parser (via the SAXBuilder class) is if you are trying to validate the correct operation of the SAXBuilder class.
Working Together: JDOM and XSLT
One of the more common questions posted to the JDOM-interest discussion list centers on using JDOM with XSLT. There are several ways to do this. Below we look at one such way using a couple of classes from the JDOM-contrib repository.
Now that we have seen how to create, input, and output a JDOM document object, let's see how to feed it into an XSLT processor to transform one JDOM document into another.
XSLT Transformations Using JDOMResult and JDOMSource
The example described later assumes that you have downloaded and installed the JDOM-contrib files from the JDOM Web site. Refer to Part 1 of this series for details on downloading and installing JDOM. The JDOM-contrib files contain two classes intended to make using JDOM with XSLT quite straightforward. These are JDOMResult and JDOMSource. You can access these, provided the JDOM-contrib.jar file is (or its classes are) in your CLASSPATH.
In addition to the JDOM-contrib files, this example also makes use of classes from the Java API for XML Processing (JAXP) 1.1.
In Listing 2 there's a transform method - in the class XSLTDemo - that takes a JDOM document and the name of an XSLT file, then using JDOMResult and JDOMSource, transforms it according to the instructions in the given XSLT file. The transform method then returns the resulting JDOM document.
I thank Laurent Bihanic for this example, and the contribution of JDOMSource and JDOMResult to the JDOM-contrib repository.
Family Matters: Working with Children
One of the useful features of JDOM is that it allows developers to add and remove elements with a single line of code in its simplest form. For example, developers can create a child element from one line of code instead of requiring a factory method to create it for them after requesting it. However, more business logic may need to be added for greater functionality.
Once you have a JDOM document, you'll want to traverse it and possibly manipulate certain elements. JDOM makes manipulation of child elements as easy as manipulating a Java 2 List. To obtain a list of child Elements belonging to a given element, use one of the getChildren methods:
List children = element.getChildren();
List children = element.getChildren
( name );
List children = element.getChildren
( name, namespace );
These methods return a list of child elements belonging to the Element, element. If no children exist, the returned list will be empty.
Any changes to the returned list object will automatically be reflected in the underlying JDOM document. Since each of these methods return a Java 2 List object, then adding, removing, and reordering children are performed using native Java 2 List operations.
For example, to create a new child Element and add it as the second child to a list, use something like the following:
Element newChild =
.setText("new child element");
children.add( 1, newChild );
Note that since the first item in a list is numbered 0, then the second item has an index of 1. Hence, the above code adds the newChild element as the second child in the list, children.
Similarly, to remove the first element (index 0) from the list, use the following:
children.remove( 0 );
The change is automatically reflected in the associated JDOM document, and the first child will be removed from the document.
As another JDOM code safety check, JDOM validates the document structure, making sure you don't have duplicate nodes above and below a child, which would result in an infinite loop. In other words, JDOM overrides the add and remove methods and makes sure there's only one parent for each child element and that that same child does not exist in a conflicting position on the tree.
This two-part series on JDOM examined in detail how this open-source Java API simplifies XML document manipulation when compared with the previous alternatives. It also describes how JDOM interacts with existing APIs for document manipulation, such as SAX and DOM. JDOM's tight, Java-centric design makes XML document creation, manipulation, transformation, and parsing a no-brainer for Java developers.
In these articles, we explored the purpose that JDOM serves in filling in the gaps where SAX and DOM fail in XML document manipulation. We also explored the JDOM API in depth, then in Part 2 we demonstrated how to use the API to perform common tasks such as inputting and outputting JDOM documents, as well as how to use JDOM with XSLT.
JDOM recently was accepted as a Java Specification Request (JSR-102) by the Java Community Process (JCP). As such, expect to hear a great deal more about JDOM in the future as it continues to be embraced by the Java community.
Special thanks to Steven Gould for sharing his expertise in JDOM and working so diligently with me on this series.
1. JDOM: www.jdom.org
2. JDOM discussion lists: www.jdom.org/involved/lists.html
3. Java API for XML Processing (JAXP): http://java.sun.com/xml/xml_jaxp.html
4. The Collections API for JDK 1.1: www.java.sun.com/products/javabeans/infobus/
5. For an alternative way of using JDOM with XSLT, see "Using JDOM and XSLT: How to Find the Right Input for Your Processor," IBM developerWorks, March 2001, by Brett McLaughlin (www-106.ibm.com/developerworks/xml/library/x-tipjdom.html).
Internet of Things (IoT) will be a hybrid ecosystem of diverse devices and sensors collaborating with operational and enterprise systems to create the next big application. In their session at @ThingsExpo, Bramh Gupta, founder and CEO of robomq.io, and Fred Yatzeck, principal architect leading product development at robomq.io, will discuss how choosing the right middleware and integration strategy from the get-go will enable IoT solution developers to adapt and grow with the industry, while at the same time reduce Time to Market (TTM) by using plug and play capabilities offered by a robust I...
Mar. 31, 2015 04:00 PM EDT Reads: 475
After making a doctor’s appointment via your mobile device, you receive a calendar invite. The day of your appointment, you get a reminder with the doctor’s location and contact information. As you enter the doctor’s exam room, the medical team is equipped with the latest tablet containing your medical history – he or she makes real time updates to your medical file. At the end of your visit, you receive an electronic prescription to your preferred pharmacy and can schedule your next appointment.
Mar. 31, 2015 03:45 PM EDT Reads: 966
SYS-CON Events announced today that Solgenia will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY, and the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Solgenia is the global market leader in Cloud Collaboration and Cloud Infrastructure software solutions. Designed to “Bridge the Gap” between Personal and Professional Social, Mobile and Cloud user experiences, our solutions help large and medium-sized organizations dr...
Mar. 31, 2015 03:00 PM EDT Reads: 2,992
While not quite mainstream yet, WebRTC is starting to gain ground with Carriers, Enterprises and Independent Software Vendors (ISV’s) alike. WebRTC makes it easy for developers to add audio and video communications into their applications by using Web browsers as their platform. But like any market, every customer engagement has unique requirements, as well as constraints. And of course, one size does not fit all. In her session at WebRTC Summit, Dr. Natasha Tamaskar, Vice President, Head of Cloud and Mobile Strategy at GENBAND, will explore what is needed to take a real time communications ...
Mar. 31, 2015 02:39 PM EDT Reads: 369
The world's leading Cloud event, Cloud Expo has launched Microservices Journal on the SYS-CON.com portal, featuring over 19,000 original articles, news stories, features, and blog entries. DevOps Journal is focused on this critical enterprise IT topic in the world of cloud computing. Microservices Journal offers top articles, news stories, and blog posts from the world's well-known experts and guarantees better exposure for its authors than any other publication. Follow new article posts on Twitter at @MicroservicesE
Mar. 31, 2015 12:00 PM EDT Reads: 1,546
SYS-CON Events announced today that Litmus Automation will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Litmus Automation’s vision is to provide a solution for companies that are in a rush to embrace the disruptive Internet of Things technology and leverage it for real business challenges. Litmus Automation simplifies the complexity of connected devices applications with Loop, a secure and scalable cloud platform.
Mar. 31, 2015 12:00 PM EDT Reads: 571
SYS-CON Events announced today the IoT Bootcamp – Jumpstart Your IoT Strategy, being held June 9–10, 2015, in conjunction with 16th Cloud Expo and Internet of @ThingsExpo at the Javits Center in New York City. This is your chance to jumpstart your IoT strategy. Combined with real-world scenarios and use cases, the IoT Bootcamp is not just based on presentations but includes hands-on demos and walkthroughs. We will introduce you to a variety of Do-It-Yourself IoT platforms including Arduino, Raspberry Pi, BeagleBone, Spark and Intel Edison. You will also get an overview of cloud technologies s...
Mar. 31, 2015 11:00 AM EDT Reads: 2,217
Containers and microservices have become topics of intense interest throughout the cloud developer and enterprise IT communities. Accordingly, attendees at the upcoming 16th Cloud Expo at the Javits Center in New York June 9-11 will find fresh new content in a new track called PaaS | Containers & Microservices Containers are not being considered for the first time by the cloud community, but a current era of re-consideration has pushed them to the top of the cloud agenda. With the launch of Docker's initial release in March of 2013, interest was revved up several notches. Then late last...
Mar. 31, 2015 09:15 AM EDT Reads: 2,290
The WebRTC Summit 2014 New York, to be held June 9-11, 2015, at the Javits Center in New York, NY, announces that its Call for Papers is open. Topics include all aspects of improving IT delivery by eliminating waste through automated business models leveraging cloud technologies. WebRTC Summit is co-located with 16th International Cloud Expo, @ThingsExpo, Big Data Expo, and DevOps Summit.
Mar. 31, 2015 09:00 AM EDT Reads: 1,693
SOA Software has changed its name to Akana. With roots in Web Services and SOA Governance, Akana has established itself as a leader in API Management and is expanding into cloud integration as an alternative to the traditional heavyweight enterprise service bus (ESB). The company recently announced that it achieved more than 90% year-over-year growth. As Akana, the company now addresses the evolution and diversification of SOA, unifying security, management, and DevOps across SOA, APIs, microservices, and more.
Mar. 31, 2015 08:30 AM EDT Reads: 2,105
Wearable technology was dominant at this year’s International Consumer Electronics Show (CES) , and MWC was no exception to this trend. New versions of favorites, such as the Samsung Gear (three new products were released: the Gear 2, the Gear 2 Neo and the Gear Fit), shared the limelight with new wearables like Pebble Time Steel (the new premium version of the company’s previously released smartwatch) and the LG Watch Urbane. The most dramatic difference at MWC was an emphasis on presenting wearables as fashion accessories and moving away from the original clunky technology associated with t...
Mar. 31, 2015 03:00 AM EDT Reads: 1,556
SYS-CON Events announced today that robomq.io will exhibit at SYS-CON's @ThingsExpo, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. robomq.io is an interoperable and composable platform that connects any device to any application. It helps systems integrators and the solution providers build new and innovative products and service for industries requiring monitoring or intelligence from devices and sensors.
Mar. 30, 2015 06:00 PM EDT Reads: 1,574
The list of ‘new paradigm’ technologies that now surrounds us appears to be at an all time high. From cloud computing and Big Data analytics to Bring Your Own Device (BYOD) and the Internet of Things (IoT), today we have to deal with what the industry likes to call ‘paradigm shifts’ at every level of IT. This is disruption; of course, we understand that – change is almost always disruptive.
Mar. 30, 2015 04:00 PM EDT Reads: 1,184
SYS-CON Events announced today that SafeLogic has been named “Bag Sponsor” of SYS-CON's 16th International Cloud Expo® New York, which will take place June 9-11, 2015, at the Javits Center in New York City, NY. SafeLogic provides security products for applications in mobile and server/appliance environments. SafeLogic’s flagship product CryptoComply is a FIPS 140-2 validated cryptographic engine designed to secure data on servers, workstations, appliances, mobile devices, and in the Cloud.
Mar. 30, 2015 11:00 AM EDT Reads: 1,547
GENBAND has announced that SageNet is leveraging the Nuvia platform to deliver Unified Communications as a Service (UCaaS) to its large base of retail and enterprise customers. Nuvia’s cloud-based solution provides SageNet’s customers with a full suite of business communications and collaboration tools. Two large national SageNet retail customers have recently signed up to deploy the Nuvia platform and the company will continue to sell the service to new and existing customers. Nuvia’s capabilities include HD voice, video, multimedia messaging, mobility, conferencing, Web collaboration, deskt...
Mar. 30, 2015 01:00 AM EDT Reads: 1,525
SYS-CON Media announced today that @WebRTCSummit Blog, the largest WebRTC resource in the world, has been launched. @WebRTCSummit Blog offers top articles, news stories, and blog posts from the world's well-known experts and guarantees better exposure for its authors than any other publication. @WebRTCSummit Blog can be bookmarked ▸ Here @WebRTCSummit conference site can be bookmarked ▸ Here
Mar. 29, 2015 10:00 PM EDT Reads: 1,868
SYS-CON Events announced today that Cisco, the worldwide leader in IT that transforms how people connect, communicate and collaborate, has been named “Gold Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Cisco makes amazing things happen by connecting the unconnected. Cisco has shaped the future of the Internet by becoming the worldwide leader in transforming how people connect, communicate and collaborate. Cisco and our partners are building the platform for the Internet of Everything by connecting the...
Mar. 29, 2015 07:00 PM EDT Reads: 5,282
Temasys has announced senior management additions to its team. Joining are David Holloway as Vice President of Commercial and Nadine Yap as Vice President of Product. Over the past 12 months Temasys has doubled in size as it adds new customers and expands the development of its Skylink platform. Skylink leads the charge to move WebRTC, traditionally seen as a desktop, browser based technology, to become a ubiquitous web communications technology on web and mobile, as well as Internet of Things compatible devices.
Mar. 29, 2015 06:00 PM EDT Reads: 1,888
Docker is an excellent platform for organizations interested in running microservices. It offers portability and consistency between development and production environments, quick provisioning times, and a simple way to isolate services. In his session at DevOps Summit at 16th Cloud Expo, Shannon Williams, co-founder of Rancher Labs, will walk through these and other benefits of using Docker to run microservices, and provide an overview of RancherOS, a minimalist distribution of Linux designed expressly to run Docker. He will also discuss Rancher, an orchestration and service discovery platf...
Mar. 29, 2015 04:15 PM EDT Reads: 2,471
SYS-CON Events announced today that Vitria Technology, Inc. will exhibit at SYS-CON’s @ThingsExpo, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Vitria will showcase the company’s new IoT Analytics Platform through live demonstrations at booth #330. Vitria’s IoT Analytics Platform, fully integrated and powered by an operational intelligence engine, enables customers to rapidly build and operationalize advanced analytics to deliver timely business outcomes for use cases across the industrial, enterprise, and consumer segments.
Mar. 29, 2015 03:30 PM EDT Reads: 2,231