Java Reference
In-Depth Information
switch
switch
(
n
.
getNodeType
()) {
case
case
Node
.
ELEMENT_NODE
:
System
.
out
.
println
(
"ELEMENT<"
+
n
.
getNodeName
() +
">"
);
doRecursive
(
n
);
break
break
;
case
case
Node
.
TEXT_NODE
:
String text
=
n
.
getNodeValue
();
iif
(
text
.
length
() ==
0
||
text
.
equals
(
"\n"
) ||
text
.
equals
(
"\\r"
)) {
break
break
;
}
System
.
out
.
println
(
"TEXT: "
+
text
);
break
break
;
default
default
:
System
.
err
.
println
(
"OTHER NODE "
+
n
.
getNodeType
() +
": "
+
n
.
getClass
());
break
break
;
}
}
}
Finding XML Elements with XPath
Problem
You want to extract elements from an XML document, without writing code to find them.
Solution
Create a
Document
instance and use the XPath API to search it.
Discussion
XPath is a World Wide Web Consortium (W3C)-defined API for searching XML documents
and performing certain operations on them. It includes a searching language that looks some-
what like a filesystem directory hierarchy (with forward slashes), so that “/people/person/
name” in our
people
example would match the person's name.
Example 20-10
shows a
simple demonstration of using XPath to retrieve a nested element containing a number rather
than a
String
.