Java Reference
In-Depth Information
Directory "TrySAXHandler 2 with extra callback methods"
I saved this as
AddressNamespace1.xml
. Unfortunately, you also have to update the DTD. Otherwise, if
the qualified names are not declared in the DTD, they are regarded as errors. You need to change the DTD
to the following:
<!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)>
Directory "TrySAXHandler 2 with extra callback methods"
I saved this as
AddressNamespaceDoc1.dtd
. The namespace prefix is
addresses
, and each element
name is qualified by the namespace prefix. You can usefully add implementations for two further callback
methods in the
MySAXHandler
class:
@Override
public void startPrefixMapping(String prefix, String uri) {
System.out.println(
"Start \"" + prefix + "\" namespace scope. URI: " + uri);
}
@Override
public void endPrefixMapping(String prefix) {
System.out.println("End \"" + prefix + "\" namespace scope.");
}
Directory "TrySAXHandler 2 with extra callback methods"
The parser doesn't call these methods by default. You have to switch the
http://xml.org/sax/features/
namespace-prefixes
feature on to get this to happen. You can add a call to the
setFeature()
method for
the parser factory object to do this in the
process()
method that you defined in the
TrySAXHandler
class,
immediately before you create the parser object in the
try
block:
spf.setFeature("http://xml.org/sax/features/namespace-prefixes",true);
parser = spf.newSAXParser();