How to use xpath to read nodes from xml file

XPath is a java library that let us read a complicated xml document with ease. In our simple example below we have an xml that contains co...

XPath is a java library that let us read a complicated xml document with ease.

In our simple example below we have an xml that contains computers with some random tags like os.

  <lenovo model="g50">
  <lenovo model="g5040">

For example if we want to get the lenovo node with year 2014, we then need to use the xpath feature with a parameter=/computers/windows/lenovo[year/text()='2014'].

package com.broodcamp.xstream_demo;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

 * @author Edward P. Legaspi
public class XPathDemo {

 public static void main(String[] args) {
  try {
   new XPathDemo();
  } catch (XPathExpressionException | ParserConfigurationException | SAXException | IOException
    | TransformerException e) {
   // TODO Auto-generated catch block

 public XPathDemo() throws ParserConfigurationException, SAXException, IOException, XPathExpressionException,
   TransformerException {
  ClassLoader classLoader = getClass().getClassLoader();
  File fXmlFile = new File(classLoader.getResource("xpath_demo.xml").getFile());

  DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
  Document doc = dBuilder.parse(fXmlFile);

  Transformer trans = TransformerFactory.newInstance().newTransformer();
  StringWriter writer = new StringWriter();
  trans.transform(new DOMSource(doc), new StreamResult(writer));
  System.out.println(writer.getBuffer().toString().replaceAll("\n|\r", ""));

  XPath xPath = XPathFactory.newInstance().newXPath();
  XPathExpression expr = xPath.compile("/computers/windows/lenovo[year/text()='2014']");
  Object result = expr.evaluate(doc, XPathConstants.NODE);

  NodeList nodes = (NodeList) result;

  for (int i = 0; i < nodes.getLength(); i++) {
   System.out.println("nodes: " + nodes.item(i).getTextContent());



javaee 7492179795639035676

Post a Comment Default Comments