Java Reference
In-Depth Information
You can see that with a DTD, the ignorable whitespace is recognized as such, and is passed to your
ig-
norableWhitespace()
method. A validating parser must call this method to report whitespace in element
content. Although the parser is validating the XML, you still can't be sure that the document is valid based
on the output you are getting. If any errors are found, the default do-nothing error-handling methods that are
inherited from the
DefaultHandler
class are called, so there's no indication of when errors are found. You
can fix this quite easily by modifying the
MySAXHandler
class, but let's first look at processing some other
XML document flavors.
Processing a Document with Namespaces
You can convert the
Address.xml
file to use a namespace by modifying the root element like this:
<address xmlns="http://www.wrox.com/AddressNamespace">
With this change to the XML file, the URI for the default namespace is
http://www.wrox.com/Ad-
dressNamespace
.
This doesn't really exist, but it doesn't need to. It's just a unique qualifier for the names
within the namespace.
You also need to use a different DTD that takes into account the use of a namespace, so you must modify
the
DOCTYPE
declaration in the document:
<!DOCTYPE address SYSTEM "AddressNamespaceDoc.dtd">
You can now save the revised XML document with the name
AddressNamespace.xml
.
You must also create the new DTD. This is the same as
AddressDoc.dtd
with the addition of a declara-
tion for the
xmlns
attribute for the
<address>
element:
<!ATTLIST address xmlns CDATA #IMPLIED>
If you run the previous example with this version of the XML document, you should see the URI in the
output. Because the namespace is the default, there is no prefix name, so the values for the
localname
and
qname
parameters to the
startElement()
and
endElement()
methods are the same.
Using Qualified Names
You can change the document to make explicit use of the namespace prefix like this:
<?xml version="1.0"?>
<!DOCTYPE addresses:address SYSTEM "AddressNamespaceDoc.dtd">
<addresses:address xmlns:addresses=" http://www.wrox.com/AddressNamespace">
<addresses:buildingnumber> 29 </addresses:buildingnumber>
<addresses:street> South Lasalle Street</addresses:street>
<addresses:city>Chicago</addresses:city>
<addresses:state>Illinois</addresses:state>
<addresses:zip>60603</addresses:zip>
</addresses:address>