title: Parsing element ( includng attribute) and text nodes of xml document using perl
body: <p>I have the following test.xml:</p>
  
  <pre><code>&lt;root&gt;
  &lt;A title="A1"&gt;
    &lt;B title="B1"&gt;
     &lt;C title="C1"&gt;
      &lt;params&gt;param=ABC1&lt;/params&gt;
      &lt;params&gt;param=ABC2&lt;/params&gt;
     &lt;/C&gt;
    &lt;/B&gt;
  &lt;/A&gt;
  &lt;D title="D1"&gt;
    &lt;B title="B2"&gt;
     &lt;C title="C2"&gt;        
       &lt;params&gt;param=DBC1&lt;/params&gt;
       &lt;params&gt;param=DBC2&lt;/params&gt;
     &lt;/C&gt;
    &lt;/B&gt;
  &lt;/D&gt;
  &lt;/root&gt;
  </code></pre>
  
  <p>I need a perl code to parse it and print a report as:</p>
  
  <pre><code>NdeName,  Attribute(s),  Param(s)
  A          A1
  B          B1
  C          C1          param=ABC1 param=ABC2
  D          D1
  B          B2
  C          C2          param=DBC1 param=DBC2  
  </code></pre>
  
  <p>I have tried using <code>getElementByTagName('param')</code> and <code>getNodeChilds</code> etc... without success. Also, what I have been using was the <a href="http://search.cpan.org/perldoc?XML%3a%3aDOM" rel="nofollow">XML::DOM</a> module.    </p>
  
  <p>Here is the code:</p>
  
  <pre><code> use XML::DOM;
   my $parser = new XML::DOM::Parser;
   my $doc = $parser-&gt;parsefile("test.xml");
   my @paramarray=();
   ParseXML($doc,"");
  
  sub ParseXML{
   my $node = $_[0];
   my $indent = $_[1];
   my $title;
  
   if ($node == null) {
    return;
   }
  
   my $type = $node-&gt;getNodeType();
   if ($type == DOCUMENT_NODE) {
    ParseXML($node-&gt;getFirstChild(),"");
    break;
   }  
  
    if ($type == ELEMENT_NODE) {
    $numberAttributes =0;
    if ($node-&gt;getAttributes() !=null){
       $numberAttributes = $node-&gt;getAttributes()-&gt;getLength();
    }
  
   for ($loopIndex =0; $loopIndex&lt;$numberAttributes; $loopIndex++) {
       $attribute = ($node-&gt;getAttributes())-&gt;item($loopIndex);
       if($attribute-&gt;getNodeName() eq "title"){
        $title = $attribute-&gt;getNodeValue();
       }
   }
  
   if ($node-&gt;getNodeName() eq "params"){
    foreach my $paramvar ($doc-&gt;getElementsByTagName("params")) {
       foreach my $child ($paramvar-&gt;getChildNodes) {
          push(@paramarray, $child-&gt;getData);
       }
    }
   }
  
  
   if ($node-&gt;getNodeName() ne "root") {
        print $node-&gt;getNodeName. ", $title, @paramarray\n";
        @paramarray=();
   } 
  
   my @childNodes = $node-&gt;getChildNodes()
   if (@childNodes != null){
     my $numberChildNodes = $#childNodes + 1;
     my $loopIndex;
    for ($loopIndex =0; $loopIndex&lt;$numberChildNodes; $loopIndex++) {
         ParseXML($childNodes[$loopIndex],$indent);
    }
   }
   }
  
    if ($type == TEXT_NODE) {
      my  $nodeText = $node-&gt;getNodeValue();
    }
  
   }
  </code></pre>