JavaでXMLコレクションが空かどうかを確認する方法は何ですか?
JavaでXMLコレクションが空かどうかを判断するには、次の方法を使用します。
- XPath式を使用して判断する。
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "count(/root/*)";
Double count = (Double) xPath.evaluate(expression, xmlDocument, XPathConstants.NUMBER);
if (count == 0) {
// xml集合为空
} else {
// xml集合不为空
}
- DOMパーサーを使用して判定する:
NodeList nodeList = xmlDocument.getElementsByTagName("elementName");
if (nodeList.getLength() == 0) {
// xml集合为空
} else {
// xml集合不为空
}
xmlDocumentはXML文書のオブジェクトを表し、elementNameは判定する要素の名前を表します。