Java Reference
In-Depth Information
The getNamespaceURI() method is passed a prefix argument that must be
mappedtoaURI.Ifthisargumentis null ,an IllegalArgumentException ob-
ject must be thrown (according to the Java documentation). When the argument is the
desired prefix value, the namespace URI is returned.
Afterinstantiatingthe XPath class,youwouldinstantiate NSContext andregister
this instance with the XPath instance by calling XPath 's void
setNamespaceContext(NamespaceContext nsContext) method.Forex-
ample, you would specify xp.setNamespaceContext(new NSContext());
after XPath xp = xpf.newXPath(); toregisterthe NSContext instancewith
xp .
All that's left to accomplish is to apply the prefix to the XPath expression, which
now becomes //tt:contact[tt:city='Chicago']/tt:name/text() be-
causethe contact , city ,and name elementsarenowpartofthedefaultnamespace,
whose URI is mapped to arbitrary prefix tt in the NSContext instance's
getNamespaceURI() method.
Compileandruntherevised XPathSearch applicationandyou'llsee John Doe
followed by Bob Jones on separate lines.
Extension Functions and Function Resolvers
The XPath API lets you define functions (via Java methods) that extend XPath's pre-
defined function repertoire by offering new features not already provided. These Java
methods cannot have side effects because XPath functions can be evaluated multiple
timesandinanyorder.Furthermore,theycannotoverridepredefinedfunctions;aJava
method with the same name as a predefined function is never executed.
Suppose you modify Listing 10-20 's XML document to include a birth element
that records a contact's date of birth information in YYYY-MM-DD format. Listing
10-24 shows the resulting XML file.
Listing 10-24. XML-based contacts database with birth information
<?xml version="1.0"?>
<contacts xmlns="http://www.tutortutor.ca/">
<contact>
<name>John Doe</name>
<birth>1953-01-02</birth>
<city>Chicago</city>
<city>Denver</city>
Search WWH ::




Custom Search