如何检查 NodeList 是否包含 children?

How to check if NodeList contains any children?

是否有一种简单易行的方法来检查我从 xpath 评估的 NodeList 是否实际包含任何 child 个节点,或者它是否只是空标签? 以这个简单的xml为例:

<shop>
  <shoes>brand1</shoes>
  <tshirt>brand2</tshirt>
  <socks>brand3</socks>
</shop>

如果我运行

 NodeList nodeList = (NodeList) path.evaluate("/shop", myDocument, XPathConstants.NODESET);

我会得到一个很好的 NodeList,我可以从中提取各种鞋子、T 恤和袜子的值。没关系。但是如果我有一个看起来像这样的 xml 怎么办:

<shop>
</shop>

运行 相同的命令会给我一个长度为 1 的节点列表,如果我已经知道它不包含任何内容,我宁愿不继续提取过程。

除了检查 nodeList.item(0).getChildNodes().getLength() == 1 之外,还有其他检查空 child 节点的方法吗?

您可以使用 "/shop/*" xpath 和 getLength() 方法检查它。像这样:

    public static void main(String[] args)
            throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {

        String myDocumentStr = "<shop><shoes>brand1</shoes><tshirt>brand2</tshirt><socks>brand3</socks></shop>";
        Node myDocument = getNode(myDocumentStr);

        XPathExpression path = XPathFactory.newInstance().newXPath().compile("/shop/*");

        NodeList nodeList = (NodeList) path.evaluate(myDocument, XPathConstants.NODESET);

        System.out.println(nodeList.getLength());

        myDocumentStr = "<shop></shop>";
        myDocument = getNode(myDocumentStr);
        nodeList = (NodeList) path.evaluate(myDocument, XPathConstants.NODESET);

        System.out.println(nodeList.getLength());
    }

    private static Node getNode(String myDocumentStr) throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();

        Node myDocument = builder.parse(new ByteArrayInputStream(myDocumentStr.getBytes()));
        return myDocument;
    }

输出:

3
0