-1

I have the following XML structure:

<doc>
    <group name="name1">
        <group name="subname1">
            <item att="att1"/>
        </group>
        <group name="subname3">
            <item att="att3"/>
        </group>
    </group>
    <group name="name2">
        <group name="subname2">
            <item att="att2"/>
        </group>
    </group>
</doc>

If I'm using dom.getDocumentElement().getElementsByTagName("group") then I get all "group" of my xmlfile (name1, subname1, subname3,.......).

How to find only the first groups(name1 and name2)?

Ashish
  • 1,943
  • 2
  • 14
  • 17
dr_yand
  • 171
  • 2
  • 11

3 Answers3

2

Try this:

dom.getDocumentElement().getElementsByTagName("group")[0];
Mike Z
  • 4,121
  • 2
  • 31
  • 53
Navaneeth
  • 883
  • 8
  • 11
0

Try this..

NodeList nodeList = doc.getElementsByTagName("doc");
for (int i = 0; i < nodeList.getLength(); i++) 
{                   
      Node node = nodeList.item(i); 

      if(node.getNodeType() == Node.ELEMENT_NODE)
      {
           Element e = (Element) node;
           NodeList resultNodeList = e.getElementsByTagName("group");
           int resultNodeListSize = resultNodeList.getLength();
           for(int j = 0 ; j < resultNodeListSize ; j++ )
           {
                 Node resultNode = resultNodeList.item(j);
                 Element fstElmnt1 = (Element) resultNode.getParentNode();
                 Log.v("name--", ""+ ( fstElmnt1.getAttribute("name")));
           }
      }
}
Hariharan
  • 24,741
  • 6
  • 50
  • 54
0

You can use XPath as explained here and use an XPath expression like this /doc/group/@name = 'name1' or /doc/group/@name = 'name2' to only retrieve groups with a set attribute-field 'name' which equals either name1 or name2.

If you want to extract only the group tags which are children of doc the XPath expression shortens to /doc/group. This will also retrieve <group name="name3"> and <group name="name4"> automatically if they are defined as children of <doc> within your XML.

Community
  • 1
  • 1
Roman Vottner
  • 12,213
  • 5
  • 46
  • 63