Wie verwende ich XPath in einem Java-Programm? Diese Frage stellte ich zunächst Tante Gurgel und fand den IBM-Artikel, den ich im vorigen Post bereits erwähnt hatte.
Nach der Anleitung des IBM-Artikels habe ich zunächst ein neues Java-Projekt in Eclipse erstellt und im Projekt-Ordner eine Datei books.xml abgelegt, die folgenden Inhalt hat:
<?xml version="1.0" encoding="UTF-8"?>
<inventory>
<book year="2000">
<title>Snow Crash</title>
<author>Neal Stephenson</author>
<publisher>Spectra</publisher>
<isbn>0553380958</isbn>
<price>14.95</price>
</book>
<book year="2005">
<title>Burning Tower</title>
<author>Larry Niven</author>
<author>Jerry Pournelle</author>
<publisher>Pocket</publisher>
<isbn>0743416910</isbn>
<price>5.99</price>
</book>
<book year="1995">
<title>Zodiac</title>
<author>Neal Stephenson</author>
<publisher>Spectra</publisher>
<isbn>0553573862</isbn>
<price>7.50</price>
</book>
<!-- more books... -->
</inventory>
Anschließend übernahm ich den Code aus Listing 4 in eine neu erstellte java-Datei (FirstTest.java):
package de.budisantoso.da.test;
import java.io.IOException;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
/**
* @author adi
*
*/
public class FirstTest {
/**
* @param args
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
*/
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("books.xml");
XPathFactory xpFactory = XPathFactory.newInstance();
XPath xpath = xpFactory.newXPath();
try {
XPathExpression expr = xpath.compile("//book
/title/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
} catch (XPathExpressionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Und … TRARA … nach dem drücken des “Run”-Knopfes erscheint folgende Ausgabe in der Konsole:
Snow Crash
Zodiac
Wie erwartet sind das die Buchtitel der Bücher von Neal
Stephenson, die in der XML-Datei zu finden waren und mittels des folgenden XPath-Ausdrucks selektiert wurden:
//book
/title/text()
Neueste Kommentare