Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book


The Java API for XML Processing (page 67) (JAXP) makes it easy to process XML data using applications written in the Java programming language. JAXP leverages the parser standards SAX (Simple API for XML Parsing) and DOM (Document Object Model) so that you can choose to parse your data as a stream of events or to build an object representation of it. The latest versions of JAXP also supports the XSLT (XML Stylesheet Language Transformations) standard, giving you control over the presentation of the data and enabling you to convert the data to other XML documents or to other formats, such as HTML. JAXP also provides namespace support, allowing you to work with XML Schemas that might otherwise have naming conflicts.

Designed to be flexible, JAXP allows you to use any XML-compliant parser from within your application. It does this with what is called a pluggability layer, which allows you to plug in an implementation of the SAX or DOM APIs. The pluggability layer also allows you to plug in an XSL processor, letting you control how your XML data is displayed.

The latest version of JAXP is JAXP 1.2, a maintenance release that adds support for XML Schema. This version is currently being finalized through the Java Community ProcessSM (JSR-63). An early access version of JAXP 1.2 is included in this Java WSDP release and is also available in the Java XML Pack.


The Simple API for XML (page 77) defines an API for an event-based parser. Being event-based means that the parser reads an XML document from beginning to end, and each time it recognizes a syntax construction, it notifies the application that is running it. The SAX parser notifies the application by calling methods from the ContentHandler interface. For example, when the parser comes to a less than symbol (<), it calls the startElement method; when it comes to character data, it calls the characters method; when it comes to the less than symbol followed by a slash (</), it calls the endElement method, and so on. To illustrate, let's look at part of the example XML document from the first section and walk through what the parser does for each line. (For simplicity, calls to the method ignorableWhiteSpace are not included.)

<priceList>[parser calls startElement]
  <coffee>  [parser calls startElement]
    <name>Mocha Java</name>  [parser calls startElement,
                characters, and endElement]
    <price>11.95</price>  [parser calls startElement,
                characters, and endElement]
  </coffee>  [parser calls endElement]

The default implementations of the methods that the parser calls do nothing, so you need to write a subclass implementing the appropriate methods to get the functionality you want. For example, suppose you want to get the price per pound for Mocha Java. You would write a class extending DefaultHandler (the default implementation of ContentHandler) in which you write your own implementations of the methods startElement and characters.

You first need to create a SAXParser object from a SAXParserFactory object. You would call the method parse on it, passing it the price list and an instance of your new handler class (with its new implementations of the methods startElement and characters). In this example, the price list is a file, but the parse method can also take a variety of other input sources, including an InputStream object, a URL, and an InputSource object.

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse("priceList.xml", handler);

The result of calling the method parse depends, of course, on how the methods in handler were implemented. The SAX parser will go through the file priceList.xml line by line, calling the appropriate methods. In addition to the methods already mentioned, the parser will call other methods such as startDocument, endDocument, ignorableWhiteSpace, and processingInstructions, but these methods still have their default implementations and thus do nothing.

The following method definitions show one way to implement the methods characters and startElement so that they find the price for Mocha Java and print it out. Because of the way the SAX parser works, these two methods work together to look for the name element, the characters "Mocha Java", and the price element immediately following Mocha Java. These methods use three flags to keep track of which conditions have been met. Note that the SAX parser will have to invoke both methods more than once before the conditions for printing the price are met.

public void startElement(..., String elementName, ...){
    inName = true;
  } else if(elementName.equals("price") && inMochaJava ){
    inPrice = true;
    inName = false;
public void characters(char [] buf, int offset, int len) {
  String s = new String(buf, offset, len);
  if (inName && s.equals("Mocha Java")) {
    inMochaJava = true;
    inName = false;
  } else if (inPrice) {
    System.out.println("The price of Mocha Java is: " + s);
    inMochaJava = false;
    inPrice = false;

Once the parser has come to the Mocha Java coffee element, here is the relevant state after the following method calls:

next invocation of startElement -- inName is true
next invocation of characters -- inMochaJava is true
next invocation of startElement -- inPrice is true
next invocation of characters -- prints price

The SAX parser can perform validation while it is parsing XML data, which means that it checks that the data follows the rules specified in the XML document's DTD. A SAX parser will be validating if it is created by a SAXParserFactory object that has had validation turned on. This is done for the SAXParserFactory object factory in the following line of code.


So that the parser knows which DTD to use for validation, the XML document must refer to the DTD in its DOCTYPE declaration. The DOCTYPE declaration should be similar to this:

<!DOCTYPE PriceList SYSTEM "priceList.DTD">


The Document Object Model (page 149), defined by the W3C DOM Working Group, is a set of interfaces for building an object representation, in the form of a tree, of a parsed XML document. Once you build the DOM, you can manipulate it with DOM methods such as insert and remove, just as you would manipulate any other tree data structure. Thus, unlike a SAX parser, a DOM parser allows random access to particular pieces of data in an XML document. Another difference is that with a SAX parser, you can only read an XML document, but with a DOM parser, you can build an object representation of the document and manipulate it in memory, adding a new element or deleting an existing one.

In the previous example, we used a SAX parser to look for just one piece of data in a document. Using a DOM parser would have required having the whole document object model in memory, which is generally less efficient for searches involving just a few items, especially if the document is large. In the next example, we add a new coffee to the price list using a DOM parser. We cannot use a SAX parser for modifying the price list because it only reads data.

Let's suppose that you want to add Kona coffee to the price list. You would read the XML price list file into a DOM and then insert the new coffee element, with its name and price. The following code fragment creates a DocumentBuilderFactory object, which is then used to create the DocumentBuilder object builder. The code then calls the parse method on builder, passing it the file priceList.xml.

DocumentBuilderFactory factory =
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("priceList.xml");

At this point, document is a DOM representation of the price list sitting in memory. The following code fragment adds a new coffee (with the name "Kona" and the price 13.50) to the price list document. Because we want to add the new coffee right before the coffee whose name is "Mocha Java", the first step is to get a list of the name elements and iterate through the list to find "Mocha Java". Using the Node interface included in the org.w3c.dom package, the code then creates a Node object for the new coffee element and also new nodes for the name and price elements. The name and price elements contain character data, so the code creates a TextNode object for each of them and appends the text nodes to the nodes representing the name and price elements.

NodeList list = document.getElementsByTagName("name");
Node thisNode = list.item(0);
  // loop through list
Node thisChild = thisNode.getChildNode();
if (thisNode.getFirstChild() instanceof org.w3c.dom.TextNode) {
  String data = thisNode.getFirstChild().getData();
if (data.equals("Mocha Java")) { 
  // new node will be inserted before Mocha Java
  Node newNode = document.createElement("coffee");
  Node nameNode = document.createElement("name");
  TextNode textNode = document.createTextNode("Kona");
Node priceNode = document.createElement("price");
  TextNode tpNode = document.createTextNode("13.50");
  thisNode.insertBefore(newNode, thisNode);

You get a DOM parser that is validating the same way you get a SAX parser that is validating: You call setValidating(true) on a DOM parser factory before using it to create your DOM parser, and you make sure that the XML document being parsed refers to its DTD in the DOCTYPE declaration.

XML Namespaces

All the names in a DTD are unique, thus avoiding ambiguity. However, if a particular XML document references more than one DTD, there is a possibility that two or more DTDs contain the same name. Therefore, the document needs to specify a namespace for each DTD so that the parser knows which definition to use when it is parsing an instance of a particular DTD.

There is a standard notation for declaring an XML Namespace, which is usually done in the root element of an XML document. In the following example namespace declaration, the notation xmlns identifies nsName as a namespace, and nsName is set to the URL of the actual namespace:

<priceList xmlns:nsName="myDTD.dtd"

Within the document, you can specify which namespace an element belongs to as follows:

<nsName:price> ...

To make your SAX or DOM parser able to recognize namespaces, you call the method setNamespaceAware(true) on your ParserFactory instance. After this method call, any parser that the parser factory creates will be namespace aware.


XML Stylesheet Language for Transformations (page 203), defined by the W3C XSL Working Group, describes a language for transforming XML documents into other XML documents or into other formats. To perform the transformation, you usually need to supply a stylesheet, which is written in the XML Stylesheet Language (XSL). The XSL stylesheet specifies how the XML data will be displayed. XSLT uses the formatting instructions in the stylesheet to perform the transformation. The converted document can be another XML document or a document in another format, such as HTML.

JAXP supports XSLT with the javax.xml.transform package, which allows you to plug in an XSLT transformer to perform transformations. The subpackages have SAX-, DOM-, and stream-specific APIs that allow you to perform transformations directly from DOM trees and SAX events. The following two examples illustrate how to create an XML document from a DOM tree and how to transform the resulting XML document into HTML using an XSL stylesheet.

Transforming a DOM Tree to an XML Document

To transform the DOM tree created in the previous section to an XML document, the following code fragment first creates a Transformer object that will perform the transformation.

TransformerFactory transFactory =
Transformer transformer = transFactory.newTransformer();

Using the DOM tree root node, the following line of code constructs a DOMSource object as the source of the transformation.

DOMSource source = new DOMSource(document);

The following code fragment creates a StreamResult object to take the results of the transformation and transforms the tree to XML.

File newXML = new File("newXML.xml");
FileOutputStream os = new FileOutputStream(newXML);
StreamResult result = new StreamResult(os);
transformer.transform(source, result);

Transforming an XML Document to an HTML Document

You can also use XSLT to convert the new XML document, newXML.xml, to HTML using a stylesheet. When writing a stylesheet, you use XML Namespaces to reference the XSL constructs. For example, each stylesheet has a root element identifying the stylesheet language, as shown in the following line of code.

<xsl:stylesheet version="1.0" xmlns:xsl=

When referring to a particular construct in the stylesheet language, you use the namespace prefix followed by a colon and the particular construct to apply. For example, the following piece of stylesheet indicates that the name data must be inserted into a row of an HTML table.

<xsl:template match="name">

The following stylesheet specifies that the XML data is converted to HTML and that the coffee entries are inserted into a row in a table.

<xsl:stylesheet version="1.0"
  <xsl:template match="priceList">
    <html><head>Coffee Prices</head>
          <xsl:apply-templates />
  <xsl:template match="name">
      <xsl:apply-templates />
  <xsl:template match="price">
      <xsl:apply-templates />

To perform the transformation, you need to obtain an XSLT transformer and use it to apply the stylesheet to the XML data. The following code fragment obtains a transformer by instantiating a TransformerFactory object, reading in the stylesheet and XML files, creating a file for the HTML output, and then finally obtaining the Transformer object transformer from the TransformerFactory object tFactory.

TransformerFactory tFactory =
String stylesheet = "prices.xsl";
String sourceId = "newXML.xml";
File pricesHTML = new File("pricesHTML.html");
FileOutputStream os = new FileOutputStream(pricesHTML);
Transformer transformer = 
  tFactory.newTransformer(new StreamSource(stylesheet)); 

The transformation is accomplished by invoking the transform method, passing it the data and the output stream.

    new StreamSource(sourceId), new StreamResult(os));
  • + Share This
  • 🔖 Save To Your Account