How to use XPath in Java
- April 28th, 2010
- Write comment
Need to use XPath in Java?
Here is a quick example, to get something from an XHTML file:
import javax.xml.xpath.*; import org.w3c.dom.*; import org.w3c.tidy.Tidy; import java.io.File; import java.io.FileInputStream; File file = new File("/abs/path/to/file"); FileInputStream xhtml = new FileInputStream(file); Tidy tidy = new Tidy(); tidy.setQuiet(true); tidy.setShowWarnings(false); Document doc = tidy.parseDOM(xhtml, null); XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); NodeList nodes = (NodeList) xpath.evaluate("XPath Expr", doc, XPathConstants.NODESET); // NodeList nodes contains now nodes.getLength() nodes, e.g. System.out.println(nodes.item(0).getNodeValue); System.out.println(nodes.item(1).getTextContent(); String fst_child = nodes.item(2).getChildNodes().item(0).getNodeValue();
For more, take a look at the javax.xml.xpath package javadoc and at the NodeList interface.


