Java Reference
In-Depth Information
Ifthe
chicago
flagissetwhenthe
cities
loopexits,thecurrent
contact
ele-
ment node's
getElementsByTagName()
method is called to return a
NodeList
of the
contact
element node's
name
element nodes (of which there should only be
one, and which I could enforce through a DTD or schema). It is now a simple matter
to extract the first item from this list, call
getFirstChild()
onthis item to return
the text node (I assume that only text appears between
<name>
and
</name>
), and
call
getNodeValue()
onthetextnodetoobtainitsvalue,whichisthenaddedtothe
contactNames
list.
Aftercompilingthissourcecode,runtheapplication.Youshouldobservethefollow-
ing output:
John Doe
Bob Jones
TraversingtheDOM'streeofnodesisatediousexerciseatbestandiserror-proneat
worst. Fortunately, XPath can greatly simplify this situation.
BeforewritingtheXPathequivalentof
Listing10-21
,
ithelpstodefinealocationpath
expression.Forthisexample,thatexpressionis
//contact[city="Chicago"]/
name/text()
, which uses a predicate to select all
contact
nodes that contain a
Chicago city
node, then select all child
name
nodes from these
contact
nodes,
and finally select all child text nodes from these
name
nodes.
this XPath expression and the XPath API to locate Chicago contacts.
Listing 10-22.
Locating Chicago contacts with the XPath API
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 javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathException;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;