Home > Articles > Web Services > XML

This chapter is from the book

This chapter is from the book

Creating a SAX-Parsing Application

Now that the JAXP APIs are set up, let's begin the task of creating an application that uses a SAX parser to parse an XML file.

Creating the CarParts.xml File

In this chapter, an XML file that describes the parts of a car will be used as an example. The XML file will be named CarParts.xml. To create it, open the text editor of your choice, copy the following code, and save the file as CarParts.xml:

<?xml version='1.0'?>
<!-- XML file that describes car parts -->
<carparts>
  <engine>
  </engine>
  <carbody>
  </carbody>
  <wheel>
  </wheel>
  <carstereo>
  </carstereo>
</carparts>

Before proceeding to write the application code, let's briefly examine the XML file. The first line

<?xml version='1.0'?>

identifies the file as an XML document.

The next line

<!--XML file that describes car parts -- >

is a comment line that describes the XML document.

The root element of the XML file is carparts and engine; carbody, wheel, and carstereo are the child elements contained within the carparts element.

As is evident, this is a very basic XML file. We will be enhancing the XML file as we progress through the chapter. Now that the XML file is created, let's go over the sequence of steps to create an application that uses a SAX parser.

Using a SAX Parser

To use a SAX parser, you must follow these steps:

  1. Import the JAXP classes.

  2. Get an instance of the SAXParserFactory class.

  3. Using the instances of the SAXParserFactory class and the SAXParser class, generate an instance of the parser. The parser wraps an implementation of the XMLReader interface, which provides the several parse() methods that can be used to parse the XML document.

  4. Get the XMLReader from the SAXParser instance.

  5. In the XMLReader, register an instance of the event-handling classes.

  6. Provide the XML document to parse.

While the parsing is in process, the XMLReader will invoke the callback methods for different parsing events, such as the start of an element, processing instructions, and so on. These callback methods are defined in the ContentHandler, ErrorHandler, DTDHandler, and EntityResolver interfaces. Normally, extending the DefaultHandler class is the most convenient way to use the methods of these interfaces.

Importing the JAXP Classes

Let's begin writing the application code that parses the CarParts.xml file. We will call the application MyXMLHandler.java. MyXMLHandler is a simple application that parses the CarParts.xml file and displays the XML structure on the command window.

The first step is to import the classes necessary for the application to access the JAXP and SAX APIs. In the MyXMLHandler.java file, add the following lines:

import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

The javax.xml.parsers package defines the JAXP APIs, the org.xml.sax package defines the interfaces used for the SAX parser, and the org.xml.sax.helpers package defines the helper classes that have the default implementations of the interfaces defined in the org.xml.sax package.

Extending the DefaultHandler Class

Next, write the class declaration by extending the DefaultHandler class and enter the main() method. To do so, enter the following lines:

public class MyXMLHandler extends DefaultHandler {
    static public void main(String[] args) throws Exception {
}

After extending the DefaultHandler class, you need to override the required ContentHandler interface methods.

Setting Up the SAX Parser

Now you will write the code to set up the SAX parser. To do so, add the lines of code in the main() method in Listing 3.1.

Listing 3.1 Setting Up the SAX Parser

/*Create a SAX Parser Factory*/
    SAXParserFactory parseFactory = SAXParserFactory.newInstance();

    /*Obtain a SAX Parser */
    SAXParser saxParser = parseFactory.newSAXParser();

    /*XML Reader is the interface for reading an XML
     document using callbacks*/
    XMLReader xmlReader = saxParser.getXMLReader();

    /*Attach ContentHandler - the callbacks like
    startDocument,startElement etc. are
     overridden by the setContentHandler to
 trap them into user code*/
    xmlReader.setContentHandler(new MyXMLHandler());

    /*Parse an XML document - the document is read and
    overridden callbacks in the MyXMLHandler are invoked*/
    xmlReader.parse("CarParts.xml");

First, we get an instance of the SAXParserFactory. The actual parser class that gets loaded depends on the value of the javax.xml.parsers.SAXParserFactory system property. In this case, the Xerces parser will be loaded, because that's the default JAXP reference implementation available with the JWSDP download.

Next, using the newSAXParser() method of the SAXParserFactory instance, get the SAXParser. From the SAXParser instance, the XMLReader is obtained by using the getXMLReader() method. The XMLReader provides the methods for parsing the XML document and generating events during the document parse. To handle the content events, pass an instance of the class that implements the ContentHandler interface using the setContentHandler() method. In this case, it will be the instance of the application itself, because it extends the DefaultHandler class. Next, using the parse() method of the XMLReader, the parser is informed of which XML file to parse.

Handling the ContentHandler Events

Once the parsing starts, events are generated whenever a valid XML syntax is found, such as the starting of an element, and the methods defined in the ContentHandler interface are called. To get any meaningful output, you need to override the required methods of the ContentHandler interface.

To override the methods of the ContentHandler interface, add the following lines in Listing 3.2 to the application. These should be placed outside the main() method.

Listing 3.2 Overriding ContentHandler Methods

public void startDocument()
    {
      System.out.println("\n Start Document:
 -----Reading the document CarParts.xml with MyXMLHandler----\n");
    }
public void startElement(String namespaceURI, String localName,
             String qualifiedName, Attributes elementAttributes)
  {
      System.out.println("Start Element-> "+qualifiedName);
  }

public void endElement(String namespaceURI, String localName
,String qualifiedName)
    {
      System.out.println("End Element-> "+qualifiedName);
    }

public void endDocument()
    {
      System.out.println("\n End Document:
----------------Finished Reading the document---------------\n");
  }

The startDocument() method is called when the parsing of the CarParts.xml file starts. The startElement() method is invoked whenever the parser finds <, representing the start of an element. In the CarParts.xml file, it will be called for each element, such as carparts, engine, and so on. Similarly, the endElement() method is invoked whenever the parser finds >.

Note that even though both the XML declaration and the comment start with <, they are not treated as elements. This is because the default behavior of the parser is to ignore both the XML declaration and comments. You can access the comments by implementing the LexicalHandler interface. This is covered in Chapter 4.

When the parsing completes (when the parser moves to the line after </carparts>), the end-document event is generated. This causes the endDocument() method to be called.

You have now successfully created an application that uses the implementation of a SAX parser (Xerces, in this case) to parse an XML document and process the data.

NOTE

The code discussed here is available in the example01 folder. This folder also contains the sample CarParts.xml file.

You can now compile the program by giving the following command in the command prompt:

javac MyXMLHandler.java

Run the program. The output should be similar to Listing 3.3.

Listing 3.3 Output of MyXMLHandler with ContentHandler

Start Document: -----Reading CarParts.xml with MyXMLHandler------

Start Element-> carparts
Start Element-> engine
End Element-> engine
Start Element-> carbody
End Element-> carbody
Start Element-> wheel
End Element-> wheel
Start Element-> carstereo
End Element-> carstereo
End Element-> carparts
End Document: ----------------Finished Reading
 the document---------------------

Handling Errors

There are times when the SAX parser runs into trouble while trying to parse an XML file. The reasons can be varied, ranging from the XML document being malformed, to inability in creating the parser itself because of some system problem, such as a missing class file, and so on.

In such cases, the parser generates an error. The error can be of three types: a fatal error, an error, and a warning.

A fatal error occurs when the parser is unable to continue the parsing of the XML document. An error occurs when the XML document fails the validity constraint, such as the presence of an invalid tag. A warning is generated when there is a problem, which although not illegal in XML, is something that might have been done inadvertently. Errors and warnings are generated only if there is a DTD and you are using a validating parser. For example, a tag might have been defined twice in the DTD. In any case, the parser generates one of the following exceptions:

  • SAXException

  • SAXParseException

  • ParserConfigurationException

SAXException and SAXParseException are generated by the callback methods when the parser finds an error in the XML file. The SAXParserFactory class generates the ParserConfigurationException if it fails to create a parser.

To handle such errors, you need to provide an exception handling mechanism. Creating a class that implements the ErrorHandler interface and registering that class with the XMLReader does this. The ErrorHandler interface has three methods: fatalError(), error(), and warning(), which handle all possible error scenarios within themselves.

You will now create an error condition in the XML file and add error-handling code to the application. To create the error condition, replace the </engine> line from the CarParts.xml file with <This_is_invalid_xml_data>.

After making the changes, the modified CarParts.xml should appear as in Listing 3.4:

Listing 3.4 CarParts.xml with Errors

<?xml version='1.0'?>
<!-- Invalid XML file that describes car parts -->

<carparts>
  <engine>
  </This_is_invalid_xml_data>
  <carbody>
  </carbody>
  <wheel>
  </wheel>
  <carstereo>
  </carstereo>
</carparts>

Next, the application needs to be updated with the error-handling code:

  1. Create a class that implements the ErrorHandler interface. For our example, we will call the class MyErrorHandler.

  2. Register the class with the XMLReader by using the setErrorHandler() method.

  3. Put a try-catch block around the parse() method to catch the exceptions. You need to catch the SAXExceptions and SAXParseExceptions to handle all parsing errors.

To create the class that implements the ErrorHandler interface, add the lines shown in Listing 3.5.

Listing 3.5 Implementing ErrorHandler

public class MyXMLHandler extends DefaultHandler{
public static void Main(String[] args) throws exception
{
  ...........
}
static class MyErrorHandler implements ErrorHandler
  {

    public void fatalError(SAXParseException saxException)
    {
      System.out.println("Fatal Error occurred "+ saxException);

    }

    public void error(SAXParseException saxException)
    {
      System.out.println("Error occurred "+ saxException);
    }

    public void warning(SAXParseException saxException)
    {
      System.out.println("warning occurred "+ saxException);
    }
  }
} //End of MyXMLHandler

You created an internal static class MyErrorHandler, which implements the ErrorHandler interface. The three methods of the ErrorHandler interface will now handle all types of errors that are generated while parsing an XML document.

Next, the class is to be registered with the XMLReader. To do so, add the following lines in bold to the application:

/*XML Reader is the interface for reading an XML document using callbacks*/
XMLReader xmlReader = saxParser.getXMLReader();

/*set the error handler*/
xmlReader.setErrorHandler(new MyErrorHandler());

xmlReader.setContentHandler(new MyXMLHandler());

Finally, the try-catch block needs to be put around the parse() method. To do so, add the lines of code displayed in Listing 3.6.

Listing 3.6 Adding the try-catch Block

xmlReader.setContentHandler(new MyXMLHandler());
try{
/*Parse an XML document - the document is read and overridden
 callbacks in the MyXMLHandler are invoked*/
    xmlReader.parse("CarParts.xml");
  }
  catch (SAXParseException saxException) {
  /* If there are errors in XML data are trapped and location is displayed*/
  System.out.println("\n\nError in data.xml at line:"
+saxException.getLineNumber()+
"("+saxException.getColumnNumber()+")\n");
  System.out.println(saxException.toString());
  }
catch (SAXException saxEx) {
  /* If there are errors in XML data, the detailed
message of the exception is displayed*/
  System.out.println(saxEx.getMessage());
  }
  } //end of main method

Now the application is capable of handling all the possible types of errors that can be generated while parsing an XML document.

NOTE

The code discussed here is available in the example02 folder. This folder also contains the sample CarParts.xml file.

Compile and run the application. The output should be similar to the following:

-----Reading the document data.xml with MyXMLHandler------

Start Element-> carparts
Start Element-> engine
Fatal Error occurred org.xml.sax.SAXParseException: Expected "</engine>"
to terminate element starting on line 5.

Error in data.xml at line:6(-1)

org.xml.sax.SAXParseException: Expected "</engine>" to terminate element
starting on line 5.

As displayed in the listing, when the parser gets a fatal error, it throws a SAXParseException and calls the fatalError() method.

So far, the parsing application can process the elements in the XML file and handle the parsing errors. Next, you will enable the application to handle element attributes.

Handling Attributes

The existing CarParts.xml file does not have any element attributes. To add attributes, update the XML file as in Listing 3.7. The element attributes that are to be added are displayed in bold.

Listing 3.7 Adding Element Attributes

<?xml version='1.0'?>
<!-- XML file that descibes car parts -->

<carparts>
  <engine type="Alpha37" capacity="2500" price="3500">
  </engine>
  <carbody type="Tallboy" color="blue">
  </carbody>
  <wheel type="X3527" price="120">
  </wheel>
  <carstereo manufacturer="MagicSound" model="T76w" Price="500">
  </carstereo>
</carparts>

After updating the XML file, update the application code to handle the attributes. There is no separate callback method per se for attributes. When the startElement() method is invoked, the list of attributes for the element is passed to the method as an Attributes object.

The attributes can be accessed in three different ways:

  • By the attribute index

  • By the namespace-qualified name

  • By the qualified (prefixed) name

In our application, the attributes are accessed by the attribute index and by the qualified (prefixed) name. The application logic is as follows: When the startElement() method is called, the application will look for an attribute called price. If the attribute named price is found, the value of the attribute is printed and the remaining attributes are ignored. If the price attribute is not found, all the attributes and their values are printed. The printing of all attributes is handled through a function named printAllAttributes(). This method takes the Attributes object as its only parameter.

First, the startElement() method is to be updated according to this logic. To do so, add the lines displayed in bold in Listing 3.8.

Listing 3.8 Accessing Element Attributes

public void startElement(String namespaceURI, String localName,
      String qualifiedName, Attributes elementAttributes)
  {
    System.out.println("Start Element-> "+qualifiedName);

    /* Get the index of price attributes*/
    int indexOfPrice=elementAttributes.getIndex("price");

    /* If a price attribute does not exist
then all the attributes are printed out*/
    /* Note that in the sample the attribute name
is case sensitive so all attributes of carstereo get printed out*/
    if(-1==indexOfPrice)
      printAllAttributes(elementAttributes);
    else
      System.out.println("\tPrice= "+
      elementAttributes.getValue("price"));
  }

Next, add the code for the printAllAttributes() method. To do so, add the lines displayed in bold.

public void printAllAttributes(Attributes elementAttributes)
  {
    System.out.println("\tTotal Number of Attributes: "+
elementAttributes.getLength());
    for(int i=0;i<elementAttributes.getLength();i++)
    {
      System.out.println("\t\tAttribute: "+
elementAttributes.getQName(i)+ " = "+elementAttributes.getValue(i));
  }

The application is all set to handle the element attributes.

NOTE

The code discussed here is available in the example03 folder. This folder also contains the sample CarParts.xml file.

Compile and execute the program. The output should be similar to Listing 3.9.

Listing 3.9 Output of MyXMLHandler with Attributes

Start Document: -----Reading CarParts.xml with MyXMLHandler------

Start Element-> carparts
  Total Number of Attributes: 0
Start Element-> engine
  Price= 3500
End Element-> engine
Start Element-> carbody
  Total Number of Attributes: 2
    Attribute: type = Tallboy
    Attribute: color = blue
End Element-> carbody
Start Element-> wheel
  Price= 120
End Element-> wheel
Start Element-> carstereo
  Total Number of Attributes: 3
    Attribute: manufacturer = MagicSound
    Attribute: model = T76w
    Attribute: Price = 500
End Element-> carstereo
End Element-> carparts

End Document: ----------------Finished Reading
 the document---------------------

Next, the application will be enhanced to handle the processing instructions.

Handling Processing Instructions

Processing instructions are declarations in which you can provide specific instructions for specific applications.

The format for a processing instruction is <?target data?>, where target is the application that is expected to do the processing, and data is the information for the application to process.

Add the lines displayed in bold in Listing 3.10 to add a processing instruction to the CarParts.xml file. Note that in addition to the processing instruction, a new element called Supplier is also being added.

Listing 3.10 Adding a Processing Instruction to CarParts.xml

<carparts>
  <?supplierformat format="X13" version="3.2"?>
  <supplier name="Car Parts Heaven" URL="http://carpartsheaven.com">
  </supplier>
  <engine id="E129" type="Alpha37" capacity="2500" price="3500">
  </engine>
  <carbody id="C32" type="Tallboy" color="blue">
  </carbody>
  <wheel id="W88" type="X3527" price="120">
  </wheel>
  <carstereo id="C2" manufacturer="MagicSound" model="T76w" Price="500">
  </carstereo>
</carparts>

Here the target application is called supplierformat, and the data that the supplierformat application has to process is format="X13" version="3.2".

The processing instructions are handled through the processingInstruction() callback method defined in the ContentHandler interface. In MyXMLHandler, override the processingInstruction() method to display the name of the target application and the data. Both of these are passed as parameters to the processingInstruction() method.

To enhance the application to handle processing instructions, add the lines displayed in bold in Listing 3.11.

Listing 3.11 Implementing the processingInstruction()Method

public void endElement(String namespaceURI, String localName,
               String qualifiedName)
{
  System.out.println("End Element-> "+qualifiedName);
}

public void processingInstruction(java.lang.String target,
                 java.lang.String data)
{
 System.out.println("Processing Instruction-> on target: "+
target+ "\n\t\t\t and data: "+data);
}

public void endDocument()
{
 System.out.println("End Document: \n----------------
 Finished Reading the document---------------\n");
}

This overrides the processingInstruction() method to display the name of the target application and the data that it will process.

NOTE

The code discussed here is available in the example04 folder. This folder also contains the sample CarParts.xml file.

Compile and run the application. The output should be similar to Listing 3.12.

Listing 3.12 Output of MyXMLHandler with Processing Instructions

Start Document: -----Reading the document CarParts.xml with MyXMLHandler------

Start Element-> carparts
  Total Number of Attributes: 0
Processing Instruction-> on target: supplierformat
       and data: format="X13" version="3.2"
Start Element-> supplier
  Total Number of Attributes: 2
    Attribute: name = Car Parts Heaven
    Attribute: URL = http://carpartsheaven.com
End Element-> supplier
Start Element-> engine
  Price= 3500
End Element-> engine
Start Element-> carbody
  Total Number of Attributes: 3
    Attribute: id = C32
    Attribute: type = Tallboy
    Attribute: color = blue
End Element-> carbody
Start Element-> wheel
  Price= 120
End Element-> wheel
Start Element-> carstereo
  Total Number of Attributes: 4
    Attribute: id = C2
    Attribute: manufacturer = MagicSound
    Attribute: model = T76w
    Attribute: Price = 500
End Element-> carstereo
End Element-> carparts

End Document: ----------------Finished Reading
 the document---------------------

The application at this point is capable of processing the elements and their attributes. It can also handle processing instructions and exceptions thrown by the SAX parser.

Next, the application will be updated to handle the content that is present between the tags.

Handling Characters

We will make the following two changes to the CarParts.xml:

  • The CarParts.xml will be enhanced to handle multiple entries of engines, wheels, car bodies, and stereos.

  • Add content between the tags.

To make the changes in the CarParts.xml file, add the lines displayed in bold in Listing 3.13.

Listing 3.13 Adding Data to Tags

<?xml version='1.0'?>
<!-- XML file that describes car parts -->

<carparts>
  <?supplierformat format="X13" version="3.2"?>
  <supplier name="Car Parts Heaven" URL="http://carpartsheaven.com">
  </supplier>
  <engines>
    <engine id="E129" type="Alpha37" capacity="2500" price="3500">
      Engine 1
    </engine>
  </engines>
  <carbodies>
    <carbody id="C32" type="Tallboy" color="blue">
      Car Body 1
    </carbody>
  </carbodies>
  <wheels>
    <wheel id="W88" type="X3527" price="120">
      Wheel Set 1
    </wheel>
  </wheels>
  <carstereos>
    <carstereo id="C2" manufacturer="MagicSound" model="T76w" Price="500">
      Car Stereo 1
    </carstereo>
  </carstereos>
</carparts>

Here you've introduced four new elements (engines, carbodies, wheels, and carstereos) to store multiple entries of engines, car bodies, wheels, and car stereos. You've also added the content between the engine, carbody, wheel, and carstereo tags. These are required to demonstrate a specific behavior of the characters() callback method.

Next, the application needs to be updated to handle the content between the tags. The content between the tags is handled by overriding the characters() callback method of the ContentHandler interface.

To override the characters() method to display the content between the tags, add the lines listed in bold in Listing 3.14.

Listing 3.14 Implementing the characters() Method

public void endElement(String namespaceURI, String localName,
               String qualifiedName)
  {
    System.out.println("End Element-> "+qualifiedName);
  }

  public void characters(char[] ch, int start, int length)
  {
    System.out.println("Characters: " + new String(ch,start,length));
  }

  public void endDocument()
  {
    System.out.println("\n End Document: ----------------Finished
Reading the document---------------------\n");
  }

This overrides the characters() method to display the text between the tags.

NOTE

The code discussed here is available in the exampl02A01 folder. This folder also contains the sample CarParts.xml file.

Compile and run the program. The output should be similar to Listing 3.15.

Listing 3.15 Output of MyXMLHandler with characters() Method

Start Document: -----Reading the document CarAPrts.xml with MyXMLHandler------

Start Element-> carparts
  Total Number of Attributes: 0
Characters:

Characters:

Start Element-> supplier
  Total Number of Attributes: 2
    Attribute: name = Car Parts Heaven
    Attribute: URL = http://carpartsheaven.com
Characters:

End Element-> supplier
Characters:

Start Element-> engines
  Total Number of Attributes: 0
Characters:

Start Element-> engine
  Price= 3500
Characters:
      Engine 1
Characters:

End Element-> engine
Characters:

End Element-> engines
Characters:

Start Element-> carbodies
  Total Number of Attributes: 0
Characters:

Start Element-> carbody
  Total Number of Attributes: 3
    Attribute: id = C32
    Attribute: type = Tallboy
    Attribute: color = blue
Characters:
      Car Body 1
Characters:

End Element-> carbody
Characters:

End Element-> carbodies
Characters:

Start Element-> wheels
  Total Number of Attributes: 0
Characters:

Start Element-> wheel
  Price= 120
Characters:
      Wheel Set 1
Characters:

End Element-> wheel
Characters:

End Element-> wheels
Characters:

Start Element-> carstereos
  Total Number of Attributes: 0
Characters:

Start Element-> carstereo
  Total Number of Attributes: 4
    Attribute: id = C2
    Attribute: manufacturer = MagicSound
    Attribute: model = T76w
    Attribute: Price = 500
Characters:
      Car Stereo 1
Characters:

End Element-> carstereo
Characters:

End Element-> carstereos
Characters:

End Element-> carparts

End Document: ----------------Finished Reading
 the document---------------------

Notice that in the output, the characters() method is called between two elements, even if the element contains child elements and no text. For example, the characters() method is called between the carbodies and carbody elements, even though the carbodies element does not contain text and only contains the carbody child element. This happens because, by default, the parser assumes that any element that it sees contains text. As you will see later, using a DTD can ensure that the parser is able to distinguish which elements contain text and which elements contain child elements.

Handling a DTD and Entities

So far, what we have seen is an XML document without a Document Type Definition (DTD). A DTD describes the structure of the content of an XML document. It defines the elements and their order and relationship with each other. A DTD also defines the element attributes and whether the element and/or attributes are mandatory or optional. You can use a DTD to ensure that the XML document is well-formed and valid. See Appendix B, "XML: A Quick Tour," to learn more about DTDs.

Next we will create a DTD for our CarParts.xml file and update our application to handle the DTD. To add the DTD to the CarParts.xml file, add the lines displayed in bold in Listing 3.16.

Note that in the DTD, we defined two entities (companyname and companyweb) and used them in the name and URL attributes of the supplier element. Entities are analogous to a macro, and they're a good way to represent information that appears multiple times in an XML document.

Listing 3.16 The DTD for CarParts.xml

<?xml version='1.0'?>
<!-- XML file that describes car parts -->

<!DOCTYPE carparts[
<!ENTITY companyname "Heaven Car Parts (TM)">
<!ENTITY companyweb "http://carpartsheaven.com">
<!ELEMENT carparts (supplier,engines,carbodies,wheels,carstereos)>
<!ELEMENT engines (engine+)>
<!ELEMENT carbodies (carbody+)>
<!ELEMENT wheels (wheel+)>
<!ELEMENT carstereos (carstereo+)>
<!ELEMENT supplier EMPTY>
<!ATTLIST supplier
      name CDATA #REQUIRED
      URL CDATA #REQUIRED
>

<!ELEMENT engine (#PCDATA)*>
<!ATTLIST engine
      id CDATA #REQUIRED
      type CDATA #REQUIRED
      capacity (1000 | 2000 | 2500 ) #REQUIRED
      price CDATA #IMPLIED
      text CDATA #IMPLIED
>
<!ELEMENT carbody (#PCDATA)*>
<!ATTLIST carbody
      id CDATA #REQUIRED
      type CDATA #REQUIRED
      color CDATA #REQUIRED
>
<!ELEMENT wheel (#PCDATA)*>
<!ATTLIST wheel
      id CDATA #REQUIRED
      type CDATA #REQUIRED
      price CDATA #IMPLIED
      size (X | Y | Z) #IMPLIED
>
<!ELEMENT carstereo (#PCDATA)*>
<!ATTLIST carstereo
      id CDATA #REQUIRED
      manufacturer CDATA #REQUIRED
      model CDATA #REQUIRED
      Price CDATA #REQUIRED
>
]>
<carparts>
  <?supplierformat format="X13" version="3.2"?>
  <supplier name="&companyname;" URL="&companyweb">
  </supplier>
  <engines>
    <engine id="E129" type="Alpha37" capacity="2500" price="3500">
      Engine 1
    </engine>
  </engines>
  <carbodies>
    <carbody id="C32" type="Tallboy" color="blue">
      Car Body 1
    </carbody>
  </carbodies>
  <wheels>
    <wheel id="W88" type="X3527" price="120">
      Wheel Set 1
    </wheel>
  </wheels>
  <carstereos>
    <carstereo id="C2" manufacturer="MagicSound" model="T76w" Price="500">
      Car Stereo 1
    </carstereo>
  </carstereos>
</carparts>

Run the application with the updated CarParts.xml file.

NOTE

The code discussed here is available in the exampl02A02 folder. This folder also contains the sample CarParts.xml file.

The output should be similar to Listing 3.17.

Listing 3.17 Output of MyXMLHandler with DTD

Start Document: -----Reading the document CarParts.xml with MyXMLHandler------

Start Element-> carparts
  Total Number of Attributes: 0
Start Element-> supplier
  Total Number of Attributes: 2
    Attribute: name = Heaven Car Parts (TM)
    Attribute: URL = http://carpartsheaven.com
Characters:

End Element-> supplier
Start Element-> engines
  Total Number of Attributes: 0
Start Element-> engine
  Price= 3500
Characters:
      Engine 1
Characters:

End Element-> engine
End Element-> engines
Start Element-> carbodies
  Total Number of Attributes: 0
Start Element-> carbody
  Total Number of Attributes: 3
    Attribute: id = C32
    Attribute: type = Tallboy
    Attribute: color = blue
Characters:
      Car Body 1
Characters:

End Element-> carbody
End Element-> carbodies
Start Element-> wheels
  Total Number of Attributes: 0
Start Element-> wheel
  Price= 120
Characters:
      Wheel Set 1
Characters:

End Element-> wheel
End Element-> wheels
Start Element-> carstereos
  Total Number of Attributes: 0
Start Element-> carstereo
  Total Number of Attributes: 4
    Attribute: id = C2
    Attribute: manufacturer = MagicSound
    Attribute: model = T76w
    Attribute: Price = 500
Characters:
      Car Stereo 1
Characters:

End Element-> carstereo
End Element-> carstereos
End Element-> carparts

 End Document: ----------------Finished Reading
  the document---------------------

Notice that with the DTD in place, the characters() method is now called only for those elements that have text following them. It is no longer called for the elements that have only child elements. However, if you want to get the whitespace between the elements that have child elements, you will need to override the ignorableWhitespace() method of the ContentHandler interface.

One of the possible scenarios in which you may override the ignorbaleWhitespace() method is when your application has to process an XML file to generate another human-readable XML file. Overriding the ignorableWhitespace() method will help retain the formatting of the XML document.

Also, the companyname and the companyweb entities have been resolved and replaced with their values in the output.

So far, we have been using a nonvalidating parser to parse the XML document. A nonvalidating parser can check whether a document is well-formed. However, it cannot determine whether the document is valid with respect to the DTD. For this, a validating parser is required.

Using a Validating Parser

To generate a validating parser, add the lines listed in bold:

static public void main(String[] args) throws Exception {
......
/*Create a SAX Parser Factory*/
    SAXParserFactory parseFactory = SAXParserFactory.newInstance();

/*Set to generate Validating SAX Parser */
  parseFactory.setValidating(true);

/*Obtain a validating SAX Parser */
    SAXParser saxParser = parseFactory.newSAXParser();
......
}

The setValidating() method sets the parser to validate the XML document as it is being parsed. All other instances of the parser created from this instance of the factory will also be validating.

NOTE

The code discussed here is available in the exampl02A03 folder. This folder also contains the sample CarParts.xml file.

Compile and run the program. The output should be similar to Listing 3.18.

Listing 3.18 Output of MyXMLHandler with Parser in Validating Mode

Version 2A03.0 of MyXMLHandler in example02A03
Start Document: -----Reading the document CarParts.xml with MyXMLHandler------

Start Element-> carparts
  Total Number of Attributes: 0
Start Element-> supplier
  Total Number of Attributes: 2
    Attribute: name = Heaven Car Parts (TM)
    Attribute: URL = http://carpartsheaven.com
Characters:

Error occurred org.xml.sax.SAXParseException:
The content of element type "supplier" must match "EMPTY".
End Element-> supplier
Start Element-> engines
  Total Number of Attributes: 0
Start Element-> engine
  Price= 3500
Characters:
      Engine 1
Characters:

End Element-> engine
End Element-> engines
Start Element-> carbodies
  Total Number of Attributes: 0
Start Element-> carbody
  Total Number of Attributes: 3
    Attribute: id = C32
    Attribute: type = Tallboy
    Attribute: color = blue
Characters:
      Car Body 1
Characters:

End Element-> carbody
End Element-> carbodies
Start Element-> wheels
  Total Number of Attributes: 0
Start Element-> wheel
  Price= 120
Characters:
      Wheel Set 1
Characters:

End Element-> wheel
End Element-> wheels
Start Element-> carstereos
  Total Number of Attributes: 0
Error occurred org.xml.sax.SAXParseException: Attribute
"price" is required and must be specified for element type "carstereo".
Error occurred org.xml.sax.SAXParseException:
Attribute "Price" must be declared for element type "carstereo".
Start Element-> carstereo
  Total Number of Attributes: 4
    Attribute: id = C2
    Attribute: manufacturer = MagicSound
    Attribute: model = T76w
    Attribute: Price = 500
Characters:
      Car Stereo 1
Characters:

End Element-> carstereo
End Element-> carstereos
End Element-> carparts

End Document: ----------------Finished Reading
 the document---------------------

Notice that the parser generates two errors related to the price attribute of the carstereo element. Going back to the CarParts.xml file, you will notice that while the DTD defines the attribute as price, the actual XML document itself has it listed as Price.

Therefore, by using a combination of DTD and a validating parser, you can ensure that your XML document is both well-formed and valid.

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