Programming Tutorials Browser Tutorials Articles Struts Tutorials Hibernate Tutorials

Search: 

  Tutorial: Easy Java/XML integration with JDOM, Part 1 - JavaWorld May 2000

Easy Java/XML integration with JDOM, Part 1 - JavaWorld May 2000

Tutorial Details:

Easy Java/XML integration with JDOM, Part 1
Easy Java/XML integration with JDOM, Part 1
By: By Jason Hunter and Brett McLaughlin
Learn about a new open source API for working with XML
DOM is an open source API designed to represent an XML document and its contents to the typical Java developer in an intuitive and straightforward way. As the name indicates, JDOM is Java optimized. It behaves like Java, it uses Java collections, and it provides a low-cost entry point for using XML. JDOM users don't need to have tremendous expertise in XML to be productive and get their jobs done.
Easy Java/XML integration with JDOM: Read the whole series!
Part 1. Learn about a new API for working with XML
Part 2. Use JDOM to create and mutate XML
JDOM interoperates well with existing standards such as the Simple API for XML (SAX) and the Document Object Model (DOM). However, it's more than a simple abstraction above those APIs. JDOM takes the best concepts from existing APIs and creates a new set of classes and interfaces that provide, in the words of one JDOM user, "the interface I expected when I first looked at org.w3c.dom." JDOM can read from existing DOM and SAX sources, and can output to DOM- and SAX-receiving components. That ability enables JDOM to interoperate seamlessly with existing program components built against SAX or DOM.
JDOM has been made available under an Apache-style, open source license. That license is among the least restrictive software licenses available, enabling developers to use JDOM in creating products without requiring them to release their own products as open source. It is the license model used by the Apache Project, which created the Apache server. In addition to making the software free, being open source enables the API to take contributions from some of the best Java and XML minds in the industry and to adapt quickly to new standards as they evolve.
The JDOM philosophy
First and foremost, the JDOM API has been developed to be straightforward for Java programmers. While other XML APIs were created to be cross-language (supporting the same API for Java, C++, and even JavaScript), JDOM takes advantage of Java's abilities by using features such as method overloading, the Collections APIs, and (behind the scenes) reflection.
To be straightforward, the API has to represent the document in a way programmers would expect. For example, how would a Java programmer expect to get the text content of an element?
This is my text content
In some APIs, an element's text content is available only as a child Node of the Element . While technically correct, that design requires the following code to access an element's content:
String content = element.getFirstChild()
.getValue();
However, JDOM makes the text content available in a more straightforward way:
String text = element.getText();
Wherever possible, JDOM makes the programmer's job easier. The rule of thumb is that JDOM should help solve 80 percent or more of Java/XML problems with 20 percent or less of the traditional effort. That does not mean that JDOM conforms to only 80 percent of the XML specification. (In fact, we expect that JDOM will be fully compliant before the 1.0 final release.) What that rule of thumb does mean is that just because something could be added to the API doesn't mean it will. The API should remain sleek.
JDOM's second philosophy is that it should be fast and lightweight. Loading and manipulating documents should be quick, and memory requirements should be low. JDOM's design definitely allows for that. For example, even the early, untuned implementation has operated more quickly than DOM and roughly on par with SAX, even though it has many more features than SAX.
Do you need JDOM?
So, do you need JDOM? It's a good question. There are existing standards already, so why invent another one? The answer is that JDOM solves a problem that the existing standards do not.
DOM represents a document tree fully held in memory. It is a large API designed to perform almost every conceivable XML task. It also must have the same API across multiple languages. Because of those constraints, DOM does not always come naturally to Java developers who expect typical Java capabilities such as method overloading, the use of standard Java object types, and simple set and get methods. DOM also requires lots of processing power and memory, making it untractable for many lightweight Web applications and programs.
SAX does not hold a document tree in memory. Instead, it presents a view of the document as a sequence of events. For example, it reports every time it encounters a begin tag and an end tag. That approach makes it a lightweight API that is good for fast reading. However, the event-view of a document is not intuitive to many of today's server-side, object oriented Java developers. SAX also does not support modifying the document, nor does it allow random access to the document.
JDOM attempts to incorporate the best of DOM and SAX. It's a lightweight API designed to perform quickly in a small-memory footprint. JDOM also provides a full document view with random access but, surprisingly, it does not require the entire document to be in memory. The API allows for future flyweight implementations that load information only when needed. Additionally, JDOM supports easy document modification through standard constructors and normal set methods.
Getting a document
JDOM represents an XML document as an instance of the org.jdom.Document class. The Document class is a lightweight class that can hold a DocType , multiple ProcessingInstruction objects, a root Element , and Comment objects. You can construct a Document from scratch without needing a factory:
Document doc = new Document(new Element("rootElement"));
In the next article, we'll discuss how easy it is to create an XML structure from scratch using JDOM. For now we'll construct our documents from a preexisting file, stream, or URL:
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(url);
You can build documents from any data source using builder classes found in the org.jdom.input package. Currently there are two builders, SAXBuilder and DOMBuilder . SAXBuilder uses a SAX parser behind the scenes to build the Document from the file; the SAXBuilder listens for the SAX events and builds a corresponding Document in memory. That approach is very fast (basically as fast as SAX), and it is the approach we recommend. DOMBuilder is another alternative that builds a JDOM Document from an existing org.w3c.dom.Document object. It allows JDOM to interface easily with tools that construct DOM trees.
JDOM's speed has the potential to improve significantly upon completion of a deferred builder that scans the XML data source but doesn't fully parse it until the information is requested. For example, element attributes don't need to be parsed until their value is requested.
Builders are also being developed that construct JDOM Document objects from SQL queries, LDAP queries, and other data formats. So, once in memory, documents are not tied to their build tool.
The SAXBuilder and DOMBuilder constructors let the user specify if validation should be turned on, as well as which parser class should perform the actual parsing duties.
public SAXBuilder(String parserClass, boolean validation);
public DOMBuilder(String adapterClass, boolean validation);
The defaults are to use Apache's open source Xerces parser and to turn off validation. Notice that the DOMBuilder doesn't take a parserClass but rather an adapterClass . That is because not all DOM parsers have the same API. To still allow user-pluggable parsers, JDOM uses an adapter class that has a common API for all DOM parsers. Adapters have been written for all the popular DOM parsers, including Apache's Xerces, Crimson, IBM's XML4J, Sun's Project X, and Oracle's parsers V1 and V2. Each one implements that standard interface by making the right method calls on the backend parser. That works somewhat similarly to JAXP ( Resources ) except it supports newer parsers that JAXP does not yet support.
Outputting a document
You can output a Document using an output tool, of which there are several standard ones available. The org.jdom.output.XMLOutputter tool is probably the most commonly used. It writes the document as XML to a specified OutputStream .
The SAXOutputter tool is another alternative. It generates SAX events based on the JDOM document, which you can then send to an application component that expects SAX events. In a similar manner, DOMOutputter creates a DOM document, which you can then supply to a DOM-receiving application component. The code to output a Document as XML looks like this:
XMLOutputter outputter = new XMLOutputter();
outputter.output(doc, System.out);
XMLOutputter takes parameters to customize the output. The first parameter is the indentation string; the second parameter indicates whether you should write new lines. For machine-to-machine communication, you can ignore the niceties of indentation and new lines for the sake of speed:
XMLOutputter outputter = new XMLOutputter("", false);
outputter.output(doc, System.out);
Here's a class that reads an XML document and prints it in a nice, readable form:
import java.io.*;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;
public class PrettyPrinter {
public static void main(String[] args) {
// Assume filename argument
String filename = args[0];
try {
// Build the document with SAX and Xerces, no validation
SAXBuilder builder = new SAXBuilder();
// Create the document
Document doc = builder.build(new File(filename));
// Output the document, use standard formatter
XMLOutputter fmt = new XMLOutputter();
fmt.output(doc, System.out);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Reading the DocType
Now let's look at how to read the details of a Document . One of the things that


 

Read Tutorial at: Click here to view the tutorial

Rate Tutorial:
Easy Java/XML integration with JDOM, Part 1 - JavaWorld May 2000

View Tutorial:
Easy Java/XML integration with JDOM, Part 1 - JavaWorld May 2000

Related Tutorials:

Displaying 1 - 50 of about 3135 Related Tutorials.

Java XML Books
, Part 2 In this second part in a several part series on XML for Java.... The java.xml.parsers package is part of the Java API for XML Processing (JAXP... Java XML Books Java XML Books  
 
JDO UNPLUGGED - PART 1
. ============================================================================== BOOKS FOR REFERENCE: 1. Java Data Objects (May... JDO - Java Data Objects Tutorials, JDO Java Data Object, JDO Tutorial, JDO UNPLUGGED - PART I JDO UNPLUGGED - PART I
 
Struts integration with EJB in JBOSS3.2
Struts and EJB Integration,Struts EJB Example,Struts EJB Struts integration with EJB in JBOSS3.2  .... JBOSS application sever has become recognized leader in the java application
 
Struts integration with EJB in WEBLOGIC7
integration with EJB in WEBLOGIC7       ... of Weblogic is WL-9). Different kinds of Enterprise Beans are 1. Session Bean.... In enterprise environment there will be heavy traffic and RPC may fail to create
 
Parsing The XML File Using JDOM Parser in JSP
Parsing The XML File Using JDOM Parser in JSP Parsing The XML File Using JDOM Parser in JSP   ...; In this example we show how to work with JDOM parser to parse the xml document. JDOM can read
 
Common Interview Questions Page -1
Common Interview Questions Page -1 Common Interview Questions Page -1       ...;       Question:1. Tell Me a Little
 
Difficult Interview Questions Page -1
Difficult Interview Questions Page -1 Difficult Interview Questions Page -1       ...;       Question 1: Tell me about yourself
 
Easy Eclipse Plugin
, so it may easier to install the Server Java distribution. Eclipse J2EE tools... Easy Eclipse Plugin Easy Eclipse Plugin... prepackaged for you to add to an EasyEclipse Distribution. An EasyEclipse Plugin may
 
JDO UNPLUGGED - PART II
JDO - Java Data Objects Tutorials, JDO Java Data Object, JDO Tutorial, JDO UNPLUGGED - PART II JDO UNPLUGGED - PART II... www.jcp.org and selecting JSR-12 or can be downloaded from sun java website. Goto
 
Reading an XML document using JDOM
Reading an XML document using JDOM, XML,XML Tutorials,Online XML Tutorial,XML Help Tutorials Reading an XML document using JDOM..., creating, manipulating, and serializing XML documents, it is a tree based Java api
 
SimplyMEPIS 6.0 Alpha 1 is available now
SimplyMEPIS 6.0 Alpha 1 is available now SimplyMEPIS 6.0 Alpha 1 is available now MEPIS has announced the alpha1... it! This gives us more time to work on integration and improvements. It was a big plus
 
Easy Struts
generation. Provide a global view of any Java project with Easy Struts... Easy Struts Easy Struts...;         The Easy Struts project
 
Constructor Chaining Exercise 1
Java: Constructor Chaining Exercise 1 Java NotesConstructor Chaining Exercise 1 Name... // Date : 5 May 2003 class ConstructorChain { public static void main
 
New Page 1
and use application data without using java code. EL was introduced in JSTL 1.0... be a map key.. If the first value is a Java Bean, then second value must be a bean... one is ${bigFive[0]} The second one is ${bigFive["1"]} EL Operators
 
How To Manage Your Username And Password The Easy And Secure Way
How To Manage Your Username And Password The Easy And Secure Way... The Easy And Secure Way      ..., there is an easy-to-use freeware see below you can download right now
 
Buy Fedora Core 3 Test 1 Linux CD's in India.
Buy Fedora Core 3 Test 1 Linux CD's in India. Fedora Core 3 Test 1 Linux Fedora Core 3 Is Available Now Available Fedora... Test 1 Linux CDs, which is distributed under GNU public license. ABOUT FEDORA
 
WEBSERVICE USING APACHE AXIS - TUTORIAL-2 AXIS FOR EJB-WEBSERVICE (part-5)
had seen parts 1 to 4 of this tutorial on exposing an EJB as XML-Webservice using Axis. This is a 7 part article.?  part-1 : Overview part-2 : deploying...-bean itself) ??????????????? a) java:RPC ????????????? ??b) java:EJB ?part-6
 
Database books Page12
to prepare for and run an installation on a Windows NT, Windows 2000, Solaris, AIX... the previous installation and does not affect any files you may have added. ... of the integration servers using New Era of Networks technologies: New Era of Networks
 
Iterative/Incremental Development
Java: Iterative/Incremental Development Java NotesIterative/Incremental Development There are many... tests individual modules and integration testing sees if the total program
 
JFreeChart - An Introduction
java chart library. David Gilbert founded the JFreeChart project in February 2000...; JFreeChart is easy to extend and it can be used for developing client side... layout managers serialization utilities a date chooser panel XML parser
 
Bayanihan Linux 4 Beta 1 has been released
Bayanihan Linux 4 Beta 1 has been released Bayanihan Linux 4 Beta 1 has been released  Bayanihan Linux 4 Beta 1 is now available... for removable devices (USB); easy to update and upgrade. Note: The beta release
 
Java Interview Questions - Page 1
Java Interview Questions,interview questions java Java Interview Questions - Page 1     ...;         Java Interview
 
String Exercises 1 - Answers
Java: String Exercises 1 - Answers Java: String Exercises 1 - Answers Answers to the String Exercises 1. 3 -- s refers to exactly the same string as a. ERROR -- t
 
Ajax Tools
;       Many resources for easy development of Ajax Applications. You can use the Ajax Tools for easy and fast development... Features: 1, efficient developing tool The JoyiStar WebShop is a visualized modeling
 
Open Source Business Model
to learn that an open source company may give its products away for free or for a minimal cost. While it is true that an open source business may not make..., Apache, and Netscape, a host of web-specific technologies such as Java, Perl
 
Open Source Database
To date, there has been no easy way to benchmark the performance of a database system. The choices were 1. Hire a consulting group... released by Inprise Corp (now known as Borland Software Corp) on 25 July, 2000
 
Wi-Fi as a part of LBS
Wi-Fi as a part of LBS Wi-Fi as a part of LBS                         
 
Core Java Interview Question Page 1
Core Java Interview Question, Interview Question Core Java Interview Question Page 1    ...: How could Java classes direct program messages to the system console
 
Simple Linked List Exercise 1
Java: Simple Linked List Exercise 1 Java Notes: Simple Linked List Exercise 1 Name... strings and puts them in a doubly linked list. 1 2 3 4 5 6
 
Eclipse Perl Integration
Eclipse Plugin-Language Eclipse Perl Integration                        
 
Hibernate Tools
; Working with Hibernate is very easy and developers enjoy using... with a unified Ant task for integration into the build cycle. Hibernate Tools is a core component of JBoss Tools and hence also part of Red Hat Developer Studio. See
 
Java Virtual Machine(JVM)
of Java architecture and it is the part of the JRE (Java Runtime Enviroment... to run. JVM is a part of Java Run Time Environment that is required by every... environment, it is impossible to run Java software. JVM forms the part
 
AN INTRODUCTION TO JSTL
on this article may be sent to:  ramrsr@rediffmail.com ) In this four-part....   Tutorial Home | Part 1 | Part 2 |  Part 3 | Part 4... specification of Java langauage itself , in future. (That yardstick may be valid for all
 
Sr. Java Developer with EJB Experience
Sr. Java Developer with EJB Experience Sr. Java...;       Position Vacant: Sr. Java...; Development Testing (UNIT testing)  Integration Tetsting 
 
Apache Myfaces and Tomahawk
rich set of components that makes easy and fast to create GUI for web... you may not decide which implementation to use. JSF implementations... of size "1" with no multiple attribute.    
 
Apatar Open Source Data Integration
Apatar Open Source Data Integration Apatar Open Source Data Integration       ...;       For Operational Integration
 
Open Source Knowlegde base Software
their full-time job, comprises a significant part of their responsibilities. The aim... users select the projects best suited for their needs, develop integration plans... such as: 1.Speech understanding 2.Database integration 3.Rapid development
 
Technology What is and FAQs
it is the part of the MPEG-4 standard.    ASCIIASCII, the abbreviation... Language is also an XML-based language like EAI the other business software... Integration. EAI works for merging the various project application into a common
 
Methods - Vocabulary
Java: Methods - Vocabulary Java NotesMethods - Vocabulary access modifier There may be an access... something. method body Amethod body is the part of the method that contains
 
VectorLinux 5.1 Live Beta 1 has been released
VectorLinux 5.1 Live Beta 1 has been released VectorLinux 5.1 Live Beta 1 has been released Well here it is. We... produced a bloat free, easy to install, configure and maintain Slackware based system
 
'if' Statement - Braces
Java: 'if' Statement - Braces Java Notes'if' Statement - Braces Braces { } not required for one statement If the true or false part of and if statement has
 
C# Programming Books
rights reserved. No part of this publication may be reproduced, stored... for ourselves. Similarly, when you write programs, unforeseen problems may arise.... Regardless of inheriting all the members, the base class members may/may
 
Difficult Interview Questions
;   Interview is an essential part of  the selection... - Page 1    Question: Tell me about yourself ? Answer... to your specifications, which may cause you to sometimes work late nights
 
Difficult Interview Questions
;   Interview is an essential part of  the selection... - Page 1    Question: Tell me about yourself ? Answer... to your specifications, which may cause you to sometimes work late nights
 
Programming: Hammurabi I - Project start
Java: Programming: Hammurabi I - Project start Java: Programming: Hammurabi I - Project start Copy these files to start your project The Hammurabi I program may require a number
 
Integrating Business Logic Tier and Integration Tier Components
Integrating Business Logic Tier and Integration Tier Components... the User. Integration tier components Hibernate maps the business objects to database using XML configuration file. Following file (User.hbm.xml) is used to map
 
MySQL Manual
of this documentation is subject to the following terms: You may create a printed..., in whole or in part, in another publication, requires the prior written consent... for easy navigation.           
 
VoIP Linux
. Recent happenings like Internet diffusion at low cost, new integration of dedicated... Softswitch. * Easy Web user administration and real-time accounting. * All...; Open Source VoIP Client for Linux windows Voice over IP tends to be part
 
Open Source Community
is completely free of licensing costs. OpenCms is based on Java and XML... will be freely exchanged, so that we may further the understanding of open source... Node You are now part of a network connecting more than a billion of people
 
Struts 2.0.0
Integration with Spring Easy integration with spring makes it an ideal framework... is the first version of Struts. Struts 2.0 is based on Web works and now its part... among java programmers due to its architecture and different tags, that helps
 
Site navigation
 

 

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2006. All rights reserved.