title: Get element name from XML in Java DOM
body: <p>I want to get the element name and print the data in the XML, but not sure how to get data under specific element.</p>
  
  <p>Here is the XML sample and my code. </p>
  
  <pre><code>   &lt;mdb&gt;
      &lt;movies&gt;
      &lt;movie id="godfather"&gt;
        &lt;title&gt;The Godfather&lt;/title&gt;
        &lt;year&gt;1972&lt;/year&gt;
        &lt;directors&gt;
          &lt;director idref="francisfordcoppola"/&gt;
        &lt;/directors&gt;
        &lt;genres&gt;
          &lt;genre&gt;Crime&lt;/genre&gt;
          &lt;genre&gt;Drama&lt;/genre&gt;
        &lt;/genres&gt;
         &lt;cast&gt;
          &lt;performer&gt;
            &lt;actor idref="marlonbrando"/&gt;
            &lt;role&gt;Don Vito Corleone&lt;/role&gt;
          &lt;/performer&gt;
       &lt;/cast&gt;
      &lt;/movie&gt;
      &lt;/movies&gt;
  
      &lt;performer id="kimnovak"&gt;
        &lt;name&gt;Marilyn Pauline Novak&lt;/name&gt;
        &lt;dob&gt;1933-02-13&lt;/dob&gt;
        &lt;pob&gt;Chicago, Illinois, USA&lt;/pob&gt;
        &lt;actedin&gt;
          &lt;movie idref="vertigo"/&gt;
        &lt;/actedin&gt;
      &lt;/performer&gt;
      &lt;/mdb&gt;
  
  
  
  try {
          File fXmlFile = new File(filename);
          DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
          DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
          Document doc = dBuilder.parse(fXmlFile);
  
          NodeList nodes = doc.getElementsByTagName("movie");
           System.out.println("nodes length"+ nodes.getLength());
          for (int i = 0; i &lt; nodes.getLength(); i++){
              Element element = (Element) nodes.item(i);
              NodeList name = element.getElementsByTagName("title");
              Element line = (Element) name.item(0);
              System.out.println(": " + line.getFirstChild().getTextContent());
  </code></pre>
  
  <p>I only want to get the element inside movie. but the following code also reads the
  <code>&lt;movie idref="vertigo"/&gt;</code> inside the performer(causes Nullpointer exception if I want to get the content);  I'm wondering if there is any possible way to avoid read the  under Performance by using DOM?</p>
  
  <pre><code>NodeList nodes = doc.getElementsByTagName("movie");
  </code></pre>
  
  <p></p>
  
  <p>My final output for the first movie should look like this</p>
  
  <pre><code>('godfather', 'The Godfather', '1972', 'Crime;Drama')
  </code></pre>