Simple XPath expression evaluation


/ Published in: Java
Save to your folder(s)



Copy this code and paste it in your HTML
  1. public static void examineXmlFile(String path) throws Exception {
  2. DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
  3. domFactory.setNamespaceAware(true); // never forget this!
  4. DocumentBuilder builder = domFactory.newDocumentBuilder();
  5. Document doc = builder.parse(path);
  6.  
  7. XPathFactory factory = XPathFactory.newInstance();
  8. XPath xpath = factory.newXPath();
  9. XPathExpression expr = xpath.compile("//node/@id");
  10.  
  11. Object result = expr.evaluate(doc, XPathConstants.NODESET);
  12.  
  13. NodeList nodes = (NodeList) result;
  14. for (int i = 0; i < nodes.getLength(); i++) {
  15. Node n = nodes.item(i);
  16. System.out.println(nodes.item(i).getNodeValue());
  17. }
  18. }

URL: http://www.ibm.com/developerworks/library/x-javaxpathapi/index.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.