【问题标题】:How to check if NodeList contains any children?如何检查 NodeList 是否包含任何子项?
【发布时间】:2017-08-21 19:03:00
【问题描述】:

是否有一种简单的方法来检查我从 xpath 评估的 NodeList 是否实际上包含任何子节点,或者它是否只是空标签? 以这个简单的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,如果我已经知道它不包含任何内容,我宁愿不继续提取过程。

除了检查是否nodeList.item(0).getChildNodes().getLength() == 1,还有其他方法可以检查空子节点吗?

【问题讨论】:

  • 查看Node 的文档你可以做nodelist.item(0).hasChildNodes()
  • nodeList.getLength();?您使用的 NodeList 的实现是什么?也许您可以分享更多代码以使您的问题更清楚。
  • nodeList.getLength() 两种情况都返回 1,nodeList.item(0).hasChildNodes() 两种情况都返回 true
  • 尝试/shop[child::*](或简单的//shop[*])只获取非空shop

标签: java xml xpath nodelist


【解决方案1】:

您可以使用"/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

【讨论】:

  • 非常感谢。这就是我想要的
猜你喜欢
  • 2014-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-05
  • 2014-04-06
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多