Home > Articles > Programming > Java

This chapter is from the book

This chapter is from the book

JAXP

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 SAX API

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, ...){
  if(elementName.equals("name")){
    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.

factory.setValidating(true); 

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 DOM API

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 =
          DocumentBuilderFactory.newInstance();
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");
  nameNode.appendChild(textNode);
  
Node priceNode = document.createElement("price");
  TextNode tpNode = document.createTextNode("13.50");
  priceNode.appendChild(tpNode);
  
newNode.appendChild(nameNode);
  newNode.appendChild(priceNode);
  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"
      xmlns:otherNsName="myOtherDTD.dtd">
...
</priceList>

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.

The XSLT API

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 =
        TransformerFactory.newInstance();
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=
          "http://www.w3.org/1999/XSL/Transform">

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">
  <tr><td>
    <xsl:apply-templates/>
  </td></tr>
</xsl:template>

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"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="priceList">
    <html><head>Coffee Prices</head>
      <body>
        <table>
          <xsl:apply-templates />
        </table>
      </body>
    </html>
  </xsl:template>
  <xsl:template match="name">
    <tr><td>
      <xsl:apply-templates />
    </td></tr>
  </xsl:template>
  <xsl:template match="price">
    <tr><td>
      <xsl:apply-templates />
    </td></tr>
  </xsl:template>
</xsl:stylesheet>

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 =
          TransformerFactory.newInstance();
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.

transformer.transform(
    new StreamSource(sourceId), new StreamResult(os));

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020