How to check if a collection in XML is empty in Java?
To check if an XML collection is empty in Java, you can use the following method:
- Evaluate with XPath expressions:
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "count(/root/*)";
Double count = (Double) xPath.evaluate(expression, xmlDocument, XPathConstants.NUMBER);
if (count == 0) {
// xml集合为空
} else {
// xml集合不为空
}
- Judge using a DOM parser:
NodeList nodeList = xmlDocument.getElementsByTagName("elementName");
if (nodeList.getLength() == 0) {
// xml集合为空
} else {
// xml集合不为空
}
xmlDocument represents the XML document object, while elementName represents the name of the element to be evaluated.