Java Reference
In-Depth Information
}
}
Don't forget to update the import statements in the example. The complete set will now be:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.ErrorHandler;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.w3c.dom.Attr;
import org.w3c.dom.NamedNodeMap;
import java.io.File;
import java.io.IOException;
You can recompile the code with these changes and run the example with the
circle
with
DTD.xml
file that we created back when we were discussing DTDs. You might want to comment out the call to
setIgnoringElementContentWhitespace()
to get the ignorable whitespace back in the output.
How It Works
All the new code to handle attributes is in the
listNodes()
method. After verifying that the current
node is an
Element
node and does have attributes, we get the collection of attributes as a
NamedNodeMap
object. We then iterate through the collection extracting each node in turn. Nodes are
indexed from zero and we obtain the number of nodes in the collection by calling its
getLength()
method. Since an attribute node is returned by the
item()
method as type
Node
, we have to cast the
return value to type
Attr
to call the methods in this interface. We output the attribute and its value,
making use of the
getName()
and
getValue()
methods for the
Attr
object in the process of
assembling the output string.
The
Attr
interface also declares a
getSpecified()
method that returns
true
if the attribute value
was explicitly set in the document rather than being a default value from the DTD. It also declares a
getOwnerElement()
method that returns an
Element
reference to the element to which this
attribute applies.
You can see from the output that the
toString()
method for the root element node results in a string
containing the entire document body, including the attributes.
Accessing the DOCTYPE Declaration
A node of type
DocumentType
encapsulates a
DOCTYPE
declaration and we have already obtained this
in the example by calling the
getDoctype()
method for the
Document
object. The output we have
obtained up to now is a little spartan so now we will remedy that. A
DOCTYPE
declaration is a little
complicated as it may have an internal set of definitions, an external subset specified by a system ID, an
external subset specified by public ID, or all three. We need to use the methods declared in the
DocumentType
interface to figure out what we have in any particular instance.