maverick
maverick

Reputation: 589

Java Retrieve child nodes with different tag names in the order in which they appear in an xml document

I have an xml file which looked something like this...

<RootElementTag>
   <ChildElementTag1 attribute1="value1" />
   <ChildElementTag1 attribute1="value2" />
   <ChildElementTag1 attribute1="value4" />
</RootElementTag>

I had to retrieve all the "ChildElementTag1" nodes and process them in the order in which they appear in the file. I used org.w3c.dom.Document.getElementsByTagName("ChildElementTag1"); which returned me a NodeList in the order in which it appears in the xml file.

Now the xml changed a bit and a new Child node with a different tag name "ChildElementTag2" is included.

<RootElementTag>
   <ChildElementTag1 attribute1="value1" />
   <ChildElementTag1 attribute1="value2" />
   <ChildElementTag2 attribute2="value3" />
   <ChildElementTag1 attribute1="value4" />
   <ChildElementTag2 attribute2="value5" />
</RootElementTag>

Is there a way to get all the 5 Child Element Nodes in the above xml snippet in the order in which they appear.

Note:- I did see org.w3c.dom.Document.getElementById() method which would need me to introduce an "id" attribute to each child node and order them based on their "id" attribute value. As of now I am not taking that approach hoping there is an easier way of doing this.

Upvotes: 0

Views: 1120

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168825

Call getChildNodes() on the RootTagElement node.


The javadoc for this method does not mention that the NodeList returned in the order in which it appears in the document.

I suspect you'll find they are in the same order as they appear in the document. OTOH, you might also look to methods listed just below the one to which I linked. Specifically getFirstChild() & getNextSibling() (which you would call on the first child, then repeatedly until null).

Upvotes: 2

Related Questions