xPath Processing for XML documents using Java
As defined earlier, XPath is a language for finding and searching information in an XML document using Path Expressions which is similar to the file system syntax.
[info]To practice more about xPath, you can visit this page[/info]
1 If you can using Eclipse or other IDE, you may create a new project.
2 Create a new class named : ReadXPath
3 Copy the following content the class created:
import org.w3c.dom.*; import javax.xml.xpath.*; import javax.xml.parsers.*; public class ReadXPath { public static void main(String[] args) { try{ String question="/jobs/item/company-name[contains(.,'T')]"; DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse("jobs.xml"); XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile(question); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); } }catch(Exception e){ e.printStackTrace(); } }
4 Download the following XML file, place it within the root folder of your project if you are using Eclipse as shown in the structure below. Otherwise, place it within the same folder as your class.
[success]Click here to download the jobs.xml file[/success]
5 Compile and run your project.
You can notice upon running the project, it prints the names of company starting with T as defined by the xPath query:
[info] String question="/jobs/item/company-name[contains(.,'T')]"; [/info]