Java Reference
In-Depth Information
End element: local name: x-coordinate qname: x-coordinate uri:
Characters:
Start element: local name: y-coordinate qname: y-coordinate uri:
Characters: 50
End element: local name: y-coordinate qname: y-coordinate uri:
Characters:
End element: local name: position qname: position uri:
Characters:
End element: local name: circle qname: circle uri:
End document:
How It Works
Much of the code in the TrySAXHandler class is the same as in the previous example. The main()
method first checks for a command line argument. If there isn't one we issue a message and end the
program. You might want to add some code following the command line argument check to make sure
the file does exist. We saw how to do this way back in the chapters on file I/O.
We then 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 we have seen previously 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
will be called for parsing events.
We have overridden six of the do-nothing methods inherited from DefaultHandler in the
MySAXHandler class and you can see from the output which ones get called. All they do is 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 qname is identical to localname .
Note how we form a String object in the characters() method from the specified sequence of
elements in the ch array. We must only access the length elements from this array that start with the
element ch(start) .
The output also shows that the characters() method is sometimes called with just whitespace passed
to the method in the ch array. 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
we have the namespace awareness feature switched on. If you comment out the statement that calls
setNamespaceAware() and recompile and re-execute the example, you will see that we only get a
qname reported. Both the local name and URI outputs will be empty.
Processing a Document with a DTD
We can run the example again with the Address.xml file in the Beg Java Stuff directory to see
how using a DTD affects processing. This should have the contents:
Search WWH ::




Custom Search