Java Reference
In-Depth Information
End document
How It Works
Much of the code in the TrySAXHandler class is the same as in the previous example. The main() meth-
od first checks for a command-line argument. If there isn't one, you output a message and end the pro-
gram. The code following the creation of the java.io.File object calls exists() for the object to make
sure the file does exist.
Next you call the static process() method with a reference to the File object for the XML document
as the argument. This method creates the XMLParser object in the way you've seen previously and then
creates a handler object of type MySAXHandler for use by the parser. The parsing process is started by
calling the parse() method for the parser object, parser , with the file reference as the first argument
and the handler reference as the second argument. This identifies the object whose methods are called
for parsing events.
You have overridden six of the do-nothing methods that are inherited from DefaultHandler in the
MySAXHandler class and the output indicates which ones are called. Your method implementations just
output a message along with the information that is passed as arguments. You can see from the output
that there is no URI for a namespace in the document, so the value for qname is identical to localname .
The output shows that the characters() method is called with just whitespace in the ch array. You could
see how much whitespace by adding another output statement for the value of length . This whitespace
is ignorable whitespace that appears between the elements, but the parser is not recognizing it as such.
This is because there is no DTD to define how elements are to be constructed in this document, so the
parser has no way to know what can be ignored.
You can see that the output shows string values for both a local name and a qname . This is because
you have the namespace awareness feature switched on. If you comment out the statement that calls
setNamespaceAware() and recompile and re-execute the example, you see that only a qname is reported.
Both the local name and URI outputs are empty.
You get all the information about the attributes, too, so the processing of attributes works without a DTD
or a schema.
Processing a Document with a DTD
You can run the example again with the Address.xml file that you saved earlier in the Beg Java Stuff
directory to see how using a DTD affects processing. This should have the following contents:
<?xml version="1.0"?>
<!DOCTYPE address SYSTEM "AddressDoc.dtd">
<address>
<buildingnumber> 29 </buildingnumber>
<street> South Lasalle Street</street>
<city>Chicago</city>
<state>Illinois</state>
<zip>60603</zip>
Search WWH ::




Custom Search