Java Reference
In-Depth Information
Document
declares three methods for locating one or more elements:
Element
getElementById(String elementId)
,
NodeList getElement-
sByTagName(String tagname)
, and
NodeList getElement-
sByTagNameNS(String namespaceURI,String localName)
. The first
methodreturnstheelementthathasan
id
attribute(asin
<img id=...>
)matching
the value specified by
elementId
, the second method returns a nodelist of a docu-
ment's elements (in document order) matching the specified
tagName
, and the third
methodisessentiallythesameasthesecondmethodexceptthatonlyelementsmatching
thegiven
localName
and
namespaceURI
arereturnedinthenodelist.Pass
"
*
"
to
namespaceURI
tomatchallnamespaces;pass
"
*
"
to
localName
tomatchalllocal
names.
The returned element node and each element node in the list implement the
org.w3c.dom.Element
interface.Thisinterfacedeclaresmethodstoreturnnodel-
istsofdescendentelementsinthetree,attributesassociatedwiththeelement,andmore.
Forexample,
String getAttribute(String name)
returnsthevalueoftheat-
tributeidentifiedby
name
,whereas
Attr getAttributeNode(String name)
returns an attribute node by name. The returned node is an implementation of the
org.w3c.dom.Attr
interface.
YounowhaveenoughinformationtoexploreanapplicationforparsinganXMLdoc-
ument and outputting the element and attribute information from the resulting DOM
tree.
Listing 10-14
presents this application's source code.
Listing 10-14.
DOMDemo
(version 1)
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;