How to traverse the nodes with the same element names?

Put your problem here if it does not fit any of the other categories.

How to traverse the nodes with the same element names?

Postby droidH » Thu Mar 14, 2013 8:35 am

This is the xml file:
Code: Select all
<?xml version="1.0" encoding="utf-8"?>
<parent>
    <child ID="1" Name="CHILD" Order="1">
        <child ID="1" Name="SUB_CHILD" Order="1">
         <child ID="2" Name="SUB_CHILD2" Order="2">
        </child>
    </child>
    <child ID="2" Name="CHILD2" Order="1">
        <child ID="1" Name="SUB_CHILD11" Order="1">
        <child ID="2" Name="SUB_CHILD22" Order="2">
        </child>
    </child>
</parent>


This is my code:
Code: Select all
Element root = mDocument.getDocumentElement();
            NodeList cat = root.getElementsByTagName("child");
            parentCount = cat.getLength();

            names = new String[parentCount];
            for (index = 0; index < parentCount; index++) {
                catParent = (Element) cat.item(index);
                names[index] = catParent.getAttribute("Name");
            }


What have I achieved?
I achieved retrieving the names CHILD and CHILD2.
Expected output is:
Name: CHILD
Name: CHILD2


The problem is, my code is also retrieving all of the names of the subchild.
So now the output is:
Name: CHILD
Name: SUB_CHILD
Name: SUB_CHILD2
Name: CHILD2
Name: SUB_CHILD11
Name: SUB_CHILD22


Can anyone help? Almost at my wits end.
droidH
Once Poster
Once Poster
 
Posts: 1
Joined: Thu Mar 14, 2013 8:27 am

Top

Return to Other Coding-Problems

Who is online

Users browsing this forum: No registered users and 18 guests