Professional Documents
Culture Documents
17 May 2005
The Java API for XML Processing (JAXP) lets you validate, parse, and transform XML using
several different APIs. JAXP provides both ease of use and vendor neutrality. This article,
the first of a two-part series introducing JAXP, shows you how to take advantage of the API's
parsing and validation features. Part 2 will cover XSL transformations using JAXP.
Java technology and XML are arguably the most important programming developments of the last
five years. As a result, APIs for working with XML in the Java language have proliferated. The two
most popular -- the Document Object Model (DOM) and the Simple API for XML (SAX) -- have
generated a tremendous amount of interest, and JDOM and data-binding APIs have followed (see
Resources). Understanding even one or two of these APIs thoroughly is quite a task; using all of
them correctly makes you a guru. However, more and more Java developers are finding that they
no longer need extensive knowledge of SAX and DOM -- thanks largely to Sun Microsystems'
JAXP toolkit. The Java API for XML Processing (JAXP) makes XML manageable for even
beginning Java programmers while still providing plenty of heft for advanced developers. That
said, even advanced developers who use JAXP often have misconceptions about the very API
they depend on.
This article assumes that you have some basic knowledge of SAX and DOM. If you're new to
XML parsing, you might want to read up on SAX and DOM first through online sources or skim
through my book (see Resources). You don't need to be fluent in callbacks or DOM Nodes, but you
should at least understand that SAX and DOM are parsing APIs. It would also help to have a basic
understanding of their differences. This article will make a lot more sense once you've picked up
these basics.
Strictly speaking, JAXP is an API, but it is more accurately called an abstraction layer. It doesn't
provide a new means of parsing XML, nor does it add to SAX or DOM, or give new functionality
Copyright IBM Corporation 2005
All about JAXP, Part 1
Trademarks
Page 1 of 13
developerWorks
ibm.com/developerWorks/
to Java and XML handling. (If you're in disbelief at this point, you're reading the right article.)
Instead, JAXP makes it easier to use DOM and SAX to deal with some difficult tasks. It also makes
it possible to handle some vendor-specific tasks that you might encounter when using the DOM
and SAX APIs, in a vendor-neutral way.
Going bigtime
In earlier versions of the Java platform, JAXP was a separate download from the core
platform. With Java 5.0, JAXP has become a staple of the Java language. If you've got the
latest version of the JDK (see Resources), then you've already got JAXP.
Without SAX, DOM, or another XML parsing API, you cannot parse XML. I have seen many
requests for a comparison of SAX, DOM, JDOM, and dom4j to JAXP, but making such
comparisons is impossible because the first four APIs serve a completely different purpose from
JAXP. SAX, DOM, JDOM, and dom4j all parse XML. JAXP provides a means of getting to these
parsers and the data that they expose, but doesn't offer a new way to parse an XML document.
Understanding this distinction is critical if you're going to use JAXP correctly. It will also most likely
put you miles ahead of many of your fellow XML developers.
If you're still dubious, make sure you have the JAXP distribution (see Going bigtime). Fire up a
Web browser and load the JAXP API docs. Navigate to the parsing portion of the API, located in
the javax.xml.parsers package. Surprisingly, you'll find only six classes. How hard can this API
be? All of these classes sit on top of an existing parser. And two of them are just for error handling.
JAXP is a lot simpler than people think. So why all the confusion?
Page 2 of 13
ibm.com/developerWorks/
developerWorks
First, the com.sun.xml.tree.XMLDocument class is not part of JAXP. It is part of Sun's Crimson
parser, packaged in earlier versions of JAXP. So the question is misleading from the start. Second,
a major purpose of JAXP is to provide vendor independence when dealing with parsers. With
JAXP, you can use the same code with Sun's XML parser, Apache's Xerces XML parser, and
Oracle's XML parser. Using a Sun-specific class, then, violates the point of using JAXP. Are
you starting to see how this subject has gotten muddied? The parser and the API in the JAXP
distribution have been lumped together, and some developers mistake classes and features from
one as part of the other, and vice versa.
Now that you can see beyond all the confusion, you're ready to move on to some code and
concepts.
Page 3 of 13
developerWorks
ibm.com/developerWorks/
different parser class as a String. With this approach, if you change the parser name, you won't
need to change any import statements, but you will still need to recompile the class. This is
obviously not a best-case solution. It would be much easier to be able to change parsers without
recompiling the class.
JAXP offers that better alternative: It lets you provide a parser as a Java system property. Of
course, when you download a distribution from Sun, you get a JAXP implementation that uses
Sun's version of Xerces. Changing the parser -- say, to Oracle's parser -- requires that you change
a classpath setting, moving from one parser implementation to another, but it does not require
code recompilation. And this is the magic -- the abstraction -- that JAXP is all about.
Page 4 of 13
ibm.com/developerWorks/
developerWorks
// SAX
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class TestSAXParsing {
public static void main(String[] args) {
try {
if (args.length != 1) {
System.err.println ("Usage: java TestSAXParsing [filename]");
System.exit (1);
}
// Get SAX Parser Factory
SAXParserFactory factory = SAXParserFactory.newInstance();
// Turn on validation, and turn off namespaces
factory.setValidating(true);
factory.setNamespaceAware(false);
SAXParser parser = factory.newSAXParser();
parser.parse(new File(args[0]), new MyHandler());
} catch (ParserConfigurationException e) {
System.out.println("The underlying parser does not support " +
" the requested features.");
} catch (FactoryConfigurationError e) {
System.out.println("Error occurred obtaining SAX Parser Factory.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
class MyHandler extends DefaultHandler {
// SAX callback implementations from ContentHandler, ErrorHandler, etc.
}
In Listing 1, you can see that two JAXP-specific problems can occur in using the factory: the
inability to obtain or configure a SAX factory, and the inability to configure a SAX parser. The
first of these problems, represented by a FactoryConfigurationError, usually occurs when the
parser specified in a JAXP implementation or system property cannot be obtained. The second
problem, represented by a ParserConfigurationException, occurs when a requested feature is
not available in the parser being used. Both are easy to deal with and shouldn't pose any difficulty
when using JAXP. In fact, you might want to write code that attempts to set several features and
gracefully handles situations where a certain feature isn't available.
A SAXParser instance is obtained once you get the factory, turn off namespace support, and turn
on validation; then parsing begins. The SAX parser's parse() method takes an instance of the
SAX HandlerBase helper class that I mentioned earlier, which your custom handler class extends.
See the code distribution to view the implementation of this class with the complete Java listing
(see Download). You also pass in the File to parse. However, the SAXParser class contains much
more than this single method.
Page 5 of 13
developerWorks
ibm.com/developerWorks/
settings. For example, you can use isValidating() to determine if the parser will -- or will not -perform validation, and isNamespaceAware() to see if the parser can process namespaces in an
XML document. These methods can give you information about what the parser can do, but users
with just a SAXParser instance -- and not the SAXParserFactory itself -- do not have the means to
change these features. You must do this at the parser factory level.
You also have a variety of ways to request parsing of a document. Instead of just accepting a File
and a SAX DefaultHandler instance, the SAXParser's parse() method can also accept a SAX
InputSource, a Java InputStream, or a URL in String form, all with a DefaultHandler instance. So
you can still parse documents wrapped in various forms.
Finally, you can obtain the underlying SAX parser (an instance of org.xml.sax.XMLReader) and
use it directly through the SAXParser's getXMLReader() method. Once you get this underlying
instance, the usual SAX methods are available. Listing 2 shows examples of the various uses of
the SAXParser class, the core class in JAXP for SAX parsing:
Up to this point, I've talked a lot about SAX, but I haven't unveiled anything remarkable or
surprising. JAXP's added functionality is fairly minor, especially where SAX is involved. This
minimal functionality makes your code more portable and lets other developers use it, either freely
or commercially, with any SAX-compliant XML parser. That's it. There's nothing more to using SAX
with JAXP. If you already know SAX, you're about 98 percent of the way there. You just need to
learn two new classes and a couple of Java exceptions, and you're ready to roll. If you've never
used SAX, it's easy enough to start now.
Page 6 of 13
ibm.com/developerWorks/
developerWorks
class names and a return type, and you are pretty much there. If you understand how SAX works
and what DOM is, you won't have any problem.
The primary difference between DOM and SAX is the structures of the APIs themselves. SAX
consists of an event-based set of callbacks, while DOM has an in-memory tree structure. With
SAX, there's never a data structure to work on (unless the developer creates one manually).
SAX, therefore, doesn't give you the ability to modify an XML document. DOM does provide this
functionality. The org.w3c.dom.Document class represents an XML document and is made up of
DOM nodes that represent the elements, attributes, and other XML constructs. So JAXP doesn't
need to fire SAX callbacks; it's responsible only for returning a DOM Document object from parsing.
java.io.File;
java.io.IOException;
java.io.OutputStreamWriter;
java.io.Writer;
// JAXP
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
// DOM
import
import
import
import
import
org.w3c.dom.Document;
org.w3c.dom.DocumentType;
org.w3c.dom.NamedNodeMap;
org.w3c.dom.Node;
org.w3c.dom.NodeList;
Page 7 of 13
developerWorks
ibm.com/developerWorks/
factory.setNamespaceAware(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File(args[0]));
// Print the document from the DOM tree and
//
feed it an initial indentation of nothing
printNode(doc, "");
} catch (ParserConfigurationException e) {
System.out.println("The underlying parser does not " +
"support the requested features.");
} catch (FactoryConfigurationError e) {
System.out.println("Error occurred obtaining Document " +
"Builder Factory.");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void printNode(Node node, String indent)
// print the DOM tree
}
Two problems can arise with this code (as with SAX in JAXP): a FactoryConfigurationError
and a ParserConfigurationException. The cause of each is the same as it is with
SAX. Either a problem is present in the implementation classes (resulting in a
FactoryConfigurationError), or the parser provided doesn't support the requested features
(resulting in a ParserConfigurationException). The only difference between DOM and SAX in
this respect is that with DOM you substitute DocumentBuilderFactory for SAXParserFactory, and
DocumentBuilder for SAXParser. It's that simple. (You can view the complete code listing, which
includes the method used to print out the DOM tree; see Download.)
Page 8 of 13
ibm.com/developerWorks/
developerWorks
If you're a little bored reading this section on DOM, you're not alone; I found it a little boring to write
because applying what you've learned about SAX to DOM is so straightforward.
Performing validation
In Java 5.0 (and JAXP 1.3), JAXP introduces a new way to validate documents. Instead of simply
using the setValidating() method on a SAX or DOM factory, validation is broken out into several
classes within the new javax.xml.validation package. I would need more space than I have in
this article to detail all the nuances of validation -- including W3C XML Schema, DTDs, RELAX NG
schemas, and other constraint models -- but if you already have some constraints, it's pretty easy
to use the new validation model and ensure that your document matches up with them.
First, convert your constraint model -- presumably a file on disk somewhere -- into a format
that JAXP can use. Load the file into a Source instance. (I'll cover Source in more detail in
Part 2; for now, just know that it represents a document somewhere, on disk, as a DOM
Document or just about anything else.) Then, create a SchemaFactory and load the schema using
SchemaFactory.newSchema(Source), which returns a new Schema object. Finally, with this Schema
object, create a new Validator object with Schema.newValidator(). Listing 5 should make
everything I've just said much clearer:
Page 9 of 13
developerWorks
ibm.com/developerWorks/
This is pretty straightforward once you get the hang of it. Type this code in yourself, or check out
the full listing (see Download).
Summary
Having read this article, you've seen almost the entire scope of JAXP:
Provide hooks into SAX
Provide hooks into DOM
Allow the parser to easily be changed out
To understand JAXP's parsing and validation features, you'll wade through very little tricky
material. The most difficult parts of putting JAXP to work are changing a system property, setting
validation through a factory instead of a parser or builder, and getting clear on what JAXP isn't.
JAXP provides a helpful pluggability layer over two popular Java and XML APIs. It makes your
code vendor neutral and lets you to change from parser to parser without ever recompiling your
parsing code. So download JAXP and go to it! Part 2 will show you how JAXP can help you
transform XML documents.
Page 10 of 13
ibm.com/developerWorks/
developerWorks
Downloads
Description
Name
Size
x-jaxp-all-about.zip
5 KB
Page 11 of 13
developerWorks
ibm.com/developerWorks/
Resources
Visit the "XML and Java technology" forum, hosted by Brett McLaughlin, for additional
information on how to work with these technologies.
Learn more about JAXP at Sun's Java and XML headquarters.
If you're new to Java programming, you can get JAXP along with a complete JDK by
downloading Java 5.0.
For an in-depth look at the new features in JAXP 1.3, read the two-part developerWorks
series "What's new in JAXP 1.3?":
Part 1 (November 2004) provides a brief overview of the JAXP specification, gives details
of the modifications to the javax.xml.parsers package, and describes a powerful schema
caching and validation framework.
Part 2 (December 2004) touches on utilities that add support for concepts defined in the
Namespaces in XML specification, and describes changes to the javax.xml.transform
package.
Find out more about the APIs under the covers of JAXP. Start with SAX 2 for Java at the SAX
Web site, and then take a look at DOM at the W3C Web site.
Download the Apache Xerces parser in its JDK 5.0 implementation.
Read "Achieving vendor independence with SAX" (developerWorks, March 2001) to learn
how to use SAX and a SAX helper class to achieve vendor independence in your SAX-based
applications.
Learn more about JDOM, an open source toolkit that provides a way to represent XML
documents in the Java language for easy and efficient reading, writing, and manipulation.
Read "Simplify XML programming with JDOM" (developerWorks, May 2001) to find out how
JDOM makes XML document manipulation easy for Java developers.
Check out dom4j, an open source library for working with XML, XPath, and XSLT on the Java
platform.
Read Brett McLaughlin's book Java & XML (O'Reilly & Associates, 2001), which explains how
Java programmers can use XML to build Web-based enterprise applications.
Learn the basics of manipulating XML documents using Java technology from Doug Tidwell's
developerWorks tutorial "XML programming in Java technology, Part 1" (January 2004). Part
2 (July 2004) looks at more difficult topics, such as working with namespaces, validating XML
documents, and building XML structures without a typical XML document. Finally, Part 3 (July
2004) shows you how to do more sophisticated tasks such as generate XML data structures,
manipulate those structures, and interface XML parsers with non-XML data sources.
Need a more basic introduction to XML? Try the developerWorks Intro to XML tutorial (August
2002) and other educational offerings, which cover the most fundamental topics.
Find out how you can become an IBM Certified Developer in XML and related technologies.
Page 12 of 13
ibm.com/developerWorks/
developerWorks
Page 13 of 13