I have the following Document object – Document myDoc.
myDoc holds an XML file by…
myDoc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(file);
Now I want to get the root of the XML file. Is there any difference between
Node firstChild = this.myDoc.getFirstChild()
and
Node firstChild = (Node)myDoc.getDocumentElement()
In the first way, firstChild holds a node root of an XML file but it will not have the depth of Node. However, in the second way, firstChild will be the root with all of the depth.
For example, I have the following XML
<inventory>
<book num="b1">
</book>
<book num="b2">
</book>
<book num="b3">
</book>
</inventory>
and file holds it.
In the 1st case, int count = firstChild.getChildNodes() gives count = 0.
The 2nd case will give count = 3.
Am I right?
The Node you get using myDoc.getFirstChild() may not be the document root if there are other nodes before the document root node – such as a comment node. Look at the example below:
When parsing the following XML file:
gives the following result:
But if I remove the comment, it gives: