Parse with XPath : XPath « XML « Java Tutorial






import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Main {
  public static void main(String[] args) throws Exception {
    XPath xpath = XPathFactory.newInstance().newXPath();
    String xpathExpression = "/howto/topic/@name";
    InputSource inputSource = new InputSource("howto.xml");

    NodeList nodes = (NodeList) xpath
        .evaluate(xpathExpression, inputSource, XPathConstants.NODESET);

    int j = nodes.getLength();

    for (int i = 0; i < j; i++) {
      System.out.println(nodes.item(i).getTextContent());
    }

  }
}








33.20.XPath
33.20.1.Parse with XPath
33.20.2.Get the W3C Node instance associated with the XPath selection supplied