Java Reference
In-Depth Information
<addresses:city>Chicago</addresses:city>
<addresses:state>Illinois</addresses:state>
<addresses:zip>60603</addresses:zip>
</addresses:address>
Unfortunately we also have to update the DTD. Otherwise if the qualified names are not declared in the
DTD they will be regarded as errors. We need to change the DTD to:
<!ELEMENT addresses:address (addresses:buildingnumber, addresses:street,
addresses:city, addresses:state, addresses:zip)>
<!ATTLIST addresses:address xmlns:addresses CDATA #IMPLIED>
<!ELEMENT addresses:buildingnumber (#PCDATA)>
<!ELEMENT addresses:street (#PCDATA)>
<!ELEMENT addresses:city (#PCDATA)>
<!ELEMENT addresses:state (#PCDATA)>
<!ELEMENT addresses:zip (#PCDATA)>
The namespace prefix is
addresses
, and the URI is the local file path. Each element name is qualified
by the namespace prefix. We can usefully add implementations for two further callback methods in our
TrySAXHandler
class:
public void startPrefixMapping(String prefix, String uri) {
System.out.println("Start \"" + prefix + "\" namespace scope. URI: " + uri);
}
public void endPrefixMapping(String prefix) {
System.out.println("End \"" + prefix + "\" namespace scope.");
}
The parser won't call these methods by default. We have to switch the
http://xml.org/sax/features/namespace-prefixes
feature on to get this to happen. We
can add a call to the
setFeature()
method for the parser factory object to do this in the
process()
method, immediately before we create the parser object in the
try
block:
spf.setFeature("http://xml.org/sax/features/namespace-prefixes",true);
parser = spf.newSAXParser();
We place it here, rather than following the call to
setValidating()
, because the method can throw
an exception of type
ParserConfigurationException
and it needs to be in a
try
block. Now the
parser will call the
startPrefixMapping()
method at the beginning of each namespace scope, and
the
endPrefixMapping()
method at the end. If you parse this document, you will see that the
qname
values are the local name qualified by the namespace prefix. You should also see that the start
and end of the namespace scope are recorded.
Handling other Parsing Events
We have only considered events arising from the recognition of document content, those declared in the
ContentHandler
interface. In fact the
DefaultHandler
class defines do-nothing methods declared
in the other three interfaces that we saw earlier. For instance, when a parsing error occurs a parser calls
a method to report the error. There are three methods for error reporting that are declared in the
ErrorHandler
interface and are implemented by the
DefaultHandler
class: