DraegerMTN DraegerMTN - 2 months ago 10
Java Question

How to check if NodeList contains any children?

Is there an easy and simple way to check if a NodeList that I evaluate from an xpath actually contains any child nodes, or if it's just empty tags?
Take this simple xml as an example:


If I run

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

I'll get a nice NodeList that I can extract the various shoes, tshirt and socks values from. That's fine. But what if I have an xml that looks like this:


Running the same command will give me a NodeList of length 1, and I'd rather not continue with the extraction process if I already know it contains nothing.

Other than checking if
nodeList.item(0).getChildNodes().getLength() == 1
, is there another way to check for empty childNodes?

Answer Source

You can check it using "/shop/*" xpath and getLength() method. Like this:

    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);


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


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

        DocumentBuilder builder = factory.newDocumentBuilder();

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