Following is the working code to evaluate the XPath expression and print the contents of all the Book elements in the XML document:
XPath xpath = XpathFactory.newInstance().newXPath();
String expression = „/Books/Book/Name/text()“;
NodeSet nameNodes = (NodeSet) xpath.evaluate(expression, new
InputSource(„Books.xml“), XpathConstants.NODESET);
//print all the names of the books
for(int i = 0 ; i
NodeSet nameNodes = (NodeSet) xpath.evaluate(expression, new InputSource("Books.xml"), XpathConstants.NODESET);
for(int i = 0 ; i
> ------------------
>
> ich kann nicht richtig nachvollziehen, wie das funktioniert.
> Und was ist genau result? ein object? wie muss ich das
> instanzieren?
Ein Object ist in Java erst mal (fast) alles :smile:
Das Beispiel bezieht sich auf JAXB 1.3, inzwischen sind einige XML Apis in die Standard Java API eingeflossen, evtl. wurden dabei einige Klassen umbenannt, jedenfalls sind in dem abgedruckten Code einige Klassen falsch benannt.
result ist eigentlich das oben initialisierte nameNodes, ein Objekt vom Typ org.w3c.dom.NodeList (NodeSet gibt es in der Standard API nicht). Korrekt müsste der Code in etwas so lauten
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
/\* ... \*/
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/Books/Book/Name/text()";
NodeList nameNodes = (NodeList) xpath.evaluate(expression,
new InputSource("Books.xml"), XPathConstants.NODESET);
// print all the names of the books
for(int i = 0 ; i
Die evaluate Methode kann unterschiedliche Typen zurückgeben, was zurückkommt hängt vom Parameter returnType ab (der zum XPath Ausdruck passen muss), siehe
http://java.sun.com/javase/6/docs/api/javax/xml/xpath/XPath.html
HTH
Heavy