Java HTML / XML How to - Read XML using XPath








Question

We would like to know how to read XML using XPath.

Answer

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/* ww  w  .ja v a 2s .  co  m*/
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Main {
  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder;
    Document doc = null;
    builder = factory.newDocumentBuilder();
    doc = builder.parse("employees.xml");
    // Create XPathFactory object
    XPathFactory xpathFactory = XPathFactory.newInstance();
    // Create XPath object
    XPath xpath = xpathFactory.newXPath();
    String name = getEmployeeNameById(doc, xpath, 4);
    System.out.println("Employee Name with ID 4: " + name);

    List<String> names = getEmployeeNameWithAge(doc, xpath, 30);
    System.out.println("Employees with 'age>30' are:"
        + Arrays.toString(names.toArray()));

    List<String> femaleEmps = getFemaleEmployeesName(doc, xpath);
    System.out.println("Female Employees names are:"
        + Arrays.toString(femaleEmps.toArray()));
  }
  private static List<String> getFemaleEmployeesName(Document doc, XPath xpath)
      throws Exception {
    List<String> list = new ArrayList<>();
    XPathExpression expr = xpath
        .compile("/Employees/Employee[gender='Female']/name/text()");
    // evaluate expression result on XML document
    NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++)
      list.add(nodes.item(i).getNodeValue());
    return list;
  }

  private static List<String> getEmployeeNameWithAge(Document doc, XPath xpath,
      int age) throws Exception {
    List<String> list = new ArrayList<>();
    XPathExpression expr = xpath.compile("/Employees/Employee[age>" + age
        + "]/name/text()");
    NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++)
      list.add(nodes.item(i).getNodeValue());
    return list;
  }

  private static String getEmployeeNameById(Document doc, XPath xpath, int id)
      throws Exception {
    String name = null;
    XPathExpression expr = xpath.compile("/Employees/Employee[@id='" + id
        + "']/name/text()");
    name = (String) expr.evaluate(doc, XPathConstants.STRING);
    return name;
  }

}

XML Document

Save as employees.xml.

<?xml version="1.0" encoding="UTF-8"?>
<Employees>/*from   ww w  . ja v a 2 s.com*/
    <Employee id="1">
        <age>29</age>
        <name>Pankaj</name>
        <gender>Male</gender>
        <role>Java Developer</role>
    </Employee>
    <Employee id="2">
        <age>35</age>
        <name>Lisa</name>
        <gender>Female</gender>
        <role>CEO</role>
    </Employee>
    <Employee id="3">
        <age>40</age>
        <name>Tom</name>
        <gender>Male</gender>
        <role>Manager</role>
    </Employee>
    <Employee id="4">
        <age>25</age>
        <name>Meghan</name>
        <gender>Female</gender>
        <role>Manager</role>
    </Employee>
</Employees>