Running this Java program demonstrating the use of XPaths to obtain possibly empty element contents:
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;
public class Try {
public static void main(String[] args) throws Exception {
String xml =
"<?xml version='1.0' encoding='UTF-8'?>"
+ "<Employees>"
+ " <Employee emplid='1111' type='admin'>"
+ " <firstname/>"
+ " <lastname>Watson</lastname>"
+ " <age>30</age>"
+ " <email>[email protected]</email>"
+ " </Employee>"
+ " <Employee emplid='2222' type='admin'>"
+ " <firstname>Sherlock</firstname>"
+ " <lastname>Homes</lastname>"
+ " <age>32</age>"
+ " <email>[email protected]</email>"
+ " </Employee>"
+ "</Employees>";
List<String> ids = Arrays.asList("1111", "2222");
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);
}
}
}
}
Will produce this output:
Employee 1111 has no first name.
Employee 2222's first name is Sherlock
Update per OP's request in comments
Running this Java program correcting OP's NodeList processing:
import java.io.StringReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
public class Try {
public static void main(String[] args) throws Exception {
String xml =
"<?xml version='1.0' encoding='UTF-8'?>"
+ "<Employees>"
+ " <Employee emplid='1111' type='admin'>"
+ " <firstname/>"
+ " <lastname>Watson</lastname>"
+ " <age>30</age>"
+ " <email>[email protected]</email>"
+ " </Employee>"
+ " <Employee emplid='2222' type='admin'>"
+ " <firstname>Sherlock</firstname>"
+ " <lastname>Homes</lastname>"
+ " <age>32</age>"
+ " <email>[email protected]</email>"
+ " </Employee>"
+ "</Employees>";
System.out.println("*************************");
String expression = "/Employees/Employee/firstname";
System.out.println(expression);
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(new InputSource(new StringReader(xml)),
XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
if (nodeList.item(i).getFirstChild() == null)
System.out.println("Employee has no first name.");
else
System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
}
}
}
Will produce this output:
/Employees/Employee/firstname
Employee has no first name.
Sherlock