Java Reference
In-Depth Information
public class BasicXPath {
public static void main(String...args) throws Exception {
String xmlSource = "src/xml/ch02/Catalog.xml";
//Get all titles with price between $5 and $9.99
xpath = "//book[price > 5.00 and price < 9.99]/title";
/* Prints:
* Value=King Lear
Value=Hamlet
*/
search(xmlSource, xpath);
}
public static void search(String fileIn, String xpathExp)
throws IOException {
// Set up the DOM parser
DocumentBuilderFactory docFactory =
DocumentBuilderFactory.newInstance();
try {
//Parse XML document
DocumentBuilder docBuilder =
docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(fileIn);
//Create XPath instance
XPath xpath = XPathFactory.newInstance().newXPath();
//Evaluate XPath expression against parsed document
NodeList nodes = (NodeList) xpath.evaluate(xpathExp,
doc, XPathConstants.NODESET);
//We could return these instead to let caller deal
for (int i = 0, len = nodes.getLength(); i < len; i++) {
Node node = nodes.item(i);
String value = node.getTextContent();
out.println("Value=" + value);
}
} catch (XPathExpressionException xpee) {
out.println(xpee);
throw new IOException("Cannot parse XPath.", xpee);
Search WWH ::




Custom Search