title: How to extract specific tag content in XML file if there are other tags with the same name inside another tag in Java?
body: <p>Currently, I'm working in parsing XML files in Java using DOM. But I have faced a problem in how to extract specific tag content from XML file if there are other tags with the same name inside another tag as the following scenario :</p>
  
  <pre><code>&lt;file&gt;
      &lt;sub-file&gt;
          &lt;a&gt; ....&lt;/a&gt;
          &lt;b&gt; ....&lt;/b&gt;
          &lt;c&gt; ....&lt;/c&gt;
      &lt;/sub-file&gt;
  
      &lt;a&gt; ..... some data here ....&lt;/a&gt;
      &lt;b&gt; ..... some data here ....&lt;/b&gt;
      &lt;c&gt; ..... some data here ....&lt;/c&gt;
  
      &lt;image&gt;
          &lt;a&gt; ....&lt;/a&gt;
          &lt;b&gt; ....&lt;/b&gt;
          &lt;c&gt; ....&lt;/c&gt;
      &lt;/image&gt;
  &lt;/file&gt;
  </code></pre>
  
  <p>So how could I extract a,b,c tags that aren't inside another (inside sub-file or image)? I tried so far this code:</p>
  
  <pre><code>    File xmlfile=new File(path);
              factory = DocumentBuilderFactory.newInstance();
              builder=  factory.newDocumentBuilder();
              document= builder.parse(xmlfile);
              document.getDocumentElement().normalize();
              filelist= document.getElementsByTagName("file");
              for(int o=0;o&lt;filelist.getLength();o++)
              {
                  Node nNode = filelist.item(o);
  
                  if (nNode.getNodeType() == Node.ELEMENT_NODE)
                  {
  
                      Element element = (Element) nNode;
                          for (int a=0; a&lt;element.getElementsByTagName("file").getLength(); a++)
                      {   
  
                              tagA=element.getElementsByTagName("a").item(a).getTextContent();
  
                              tagB=element.getElementsByTagName("b").item(a).getTextContent();
  
                              tagC=element.getElementsByTagName("c").item(a).getTextContent();
  
                      }       
                  }
              }// loop
          }
  </code></pre>
  
  <p>This code print all the tags a,b,c 3 times (inside file, sub-file and image).</p>