środa, 15 lipca 2009

XPath

public static void main(String[] args) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {
xmlParser app = new xmlParser();
//app.parse();

app.findBooksGenreRomance();

}

private void findBooksGenreRomance() throws ParserConfigurationException,
SAXException, IOException, XPathExpressionException {

DocumentBuilderFactory domFactory = DocumentBuilderFactory
.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("books.xml");

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr1 = xpath.compile("//book[genre='Romance']");

Object result1 = expr1.evaluate(doc, XPathConstants.NODESET);
NodeList nodes1 = (NodeList) result1;

for (int i = 1; i < nodes1.getLength()+1; i++) {
System.out.println("Book " + i + ":");

XPathExpression expr = xpath.compile("//book[genre='Romance']["+i+"]/*/text()");

Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int x = 0; x < nodes.getLength(); x++) {
System.out.println(nodes.item(x).getNodeValue());
}

System.out.println("##########################################");
}

}

Brak komentarzy:

Prześlij komentarz