2

We are studying how to parse through the DOM tree in Java. Quick question, in the below partial code my prof gave us, he creates an ArrayList and adds the Document object to it. I've only used the ArrayList to add items to the list like String, int, etc. In this case, when he adds the Document object to it, does Java automatically put each Node into the list?

       DocumentBuilder docBuilder = 
           DocumentBuilderFactory.newInstance().newDocumentBuilder(); 

        Document doc = docBuilder.parse(f); 

        List<Node> nodeList = new ArrayList<Node>(); 
        nodeList.add(doc); 

        while(nodeList.size() > 0) 

Thanks!

2 Answers 2

1

No. Document is a subtype of Node, so adding the Document to the List<Node> just adds that one object, not the child nodes of the document.

Sign up to request clarification or add additional context in comments.

Comments

0

The right way to iterate through a Document is by starting with the root and recursively visiting each child node. There are a lot of ways to do it: depth first, breadth first, etc.

I don't see the value in adding the Document to a List, unless you're creating multiple Documents at the same time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.