Java HTML / XML How to - Handle null XML tags using XPATH








Question

We would like to know how to handle null XML tags using XPATH.

Answer

import java.io.StringReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
import java.util.Arrays;
import java.util.List;
//from ww w .j a  v a 2  s . c o  m
public class Main {
    public static void main(String[] args) throws Exception {
        String xml =
          "<?xml version='1.0' encoding='UTF-8'?>"
          + "<Employees>"
          + "  <Employee emplid='1' type='admin'>"
          + "    <firstname/>"
          + "    <lastname>A</lastname>"
          + "    <age>30</age>"
          + "    <email>j@s.com</email>"
          + "  </Employee>"
          + "  <Employee emplid='2' type='admin'>"
          + "    <firstname>S</firstname>"
          + "    <lastname>H</lastname>"
          + "    <age>32</age>"
          + "    <email>s@h.com</email>"
          + "  </Employee>"
          + "</Employees>";
        List<String> ids = Arrays.asList("1", "2");
        for(int i = 0; i < ids.size(); i++) {
          String employeeId = ids.get(i);
          String xpath = "/Employees/Employee[@emplid='" + employeeId + "']/firstname";
          XPath xPath = XPathFactory.newInstance().newXPath();
          String employeeFirstName = xPath.evaluate(xpath, new InputSource(new StringReader(xml)));
          if (employeeFirstName == "") {
            System.out.println("Employee " + employeeId +  " has no first name.");
          } else {
            System.out.println("Employee " + employeeId + "'s first name is " + employeeFirstName);
          }
        }
    }
}