title: How to detect whether XML elements have child elements
body: <p>I am using the CPAN <a href="http://metacpan.org/module/XML::LibXML" rel="nofollow"><code>XML::LibXML</code></a> module to process the XML data below. I need to to determine whether each element has a child element or not. Searching around I can't find any example for that purpose.</p>
  
  <pre><code>&lt;A&gt;
      &lt;ts&gt;2012&lt;/ts&gt;
      &lt;T&gt;M1&lt;/T&gt;
      &lt;T&gt;M2&lt;/T&gt;
      &lt;B&gt;
          &lt;id&gt;PC&lt;/id&gt;
          &lt;r&gt;10&lt;/r&gt;
          &lt;r&gt;30&lt;/r&gt;
      &lt;/B&gt;
  &lt;/A&gt;
  </code></pre>
  
  <p>This is the Perl code I havae written</p>
  
  <pre><code>#!/usr/bin/perl
  
  use strict;
  use warnings;
  
  use XML::LibXML;
  
  my ($x,$elname,$haschild)= ();
  my $parser = XML::LibXML-&gt;new();
  my $npo    = $parser-&gt;parse_file("test.xml");
  my $rootel = $npo -&gt; getDocumentElement();
  $elname = $rootel -&gt; nodeName();
  print "Root name=$elname\n";
  
  foreach $x ($rootel-&gt;childNodes) {
      $elname = $x -&gt; nodeName();
      $haschild = $x-&gt;hasChildNodes;
      print "Child name = $elname and has child = $haschild.\n" unless ($elname =~ /#text/i);
  }
  </code></pre>
  
  <p>While I used <code>childNodes</code> to go through each node, I just can't find an easy way to determine whether the node has a child or not. </p>
  
  <p>I am expecting to get result after looping through all the nodes that:</p>
  
  <pre><code>A: Has children
  ts: Has none
  T: has none
  T: has none
  B: Has children
  id: Has none
  r: Has none
  r: Has none
  </code></pre>
  
  <p>The result I am getting is like this:</p>
  
  <pre><code>Root name=A
  Child name = ts and has child = 1.
  Child name = T and has child = 1.
  Child name = T and has child = 1.
  Child name = B and has child = 1.
  </code></pre>
  
  <p>It seems all nodes return true after the <code>hasChildNodes</code> condition check.</p>