Posted By

studioevoque on 09/26/11


Tagged

XPath


Versions (?)

Simple XPath expression evaluation


 / Published in: Java
 

URL: http://www.ibm.com/developerworks/library/x-javaxpathapi/index.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. }

Report this snippet  

You need to login to post a comment.