Java HTML / XML How to - Get node List from XPath








Question

We would like to know how to get node List from XPath.

Answer

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
/* w w  w  .j a v  a2s  .c o  m*/
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Main {

  public static void main(String[] args) throws Exception {

    InputSource ins = new InputSource("c:/data.xml");
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList list = (NodeList) xpath.evaluate("//bar/text()", ins,
        XPathConstants.NODESET);
    for (int i = 0; i < list.getLength(); i++) {
      System.out.println(list.item(i).getNodeValue());
    }

  }
}

data.xml

<?xml version="1.0"?>
<foo>
    <bar>hello</bar>
    <bar>ohayoo</bar>
    <bar>hola</bar>
</foo>