title: Perl XML to CSV Parse
body: <p>I have been trying to figure out how to get an xml data source parsed into a CSV file and it's driving me a little crazy. I have a data source that I need to parse an create a CSV. I also need to be able to include the Node ID as a column. Here is what I have:</p>
  
  <pre><code>         #!/usr/bin/perl
              use warnings;
          use strict;
          use XML::XPath;
  
          #Name of the CSV File
          my $filename = "parse.csv";
  
          #Create the file.
          open(INPUT,"&gt;$filename") or die "Cannot create file";
  
          #Collect the XML and set nodes
          my($xp) = XML::XPath-&gt;new( join('', &lt;DATA&gt;) );
          my(@records) = $xp-&gt;findnodes( '/CATALOG/CD' );
          my($firstTime) = 0;
  
          #Loop through each record
          foreach my $record ( @records ) {
              my(@fields) = $xp-&gt;find( './child::*', $record )-&gt;get_nodelist();
              unless ( $firstTime++ ) {
              #Print Headers
                  print( join( ',', map { $_-&gt;getName() } @fields ), "\n");
              }
              #Print Content
                  print( join( ',', map { $_-&gt;string_value() } @fields ), "\n");
          }
          #Close the file.
          close(INPUT);
  
  
          __DATA__
          &lt;FOOD&gt;
              &lt;ITEM id='1'&gt;
                  &lt;Color&gt;Brown&lt;/Color&gt;
                  &lt;Name&gt;Steak&lt;/Name&gt;
              &lt;/ITEM&gt;
              &lt;ITEM id='2'&gt;
                  &lt;Color&gt;Blue&lt;/Color&gt;
                  &lt;Name&gt;Blueberries&lt;/Name&gt;
              &lt;/ITEM&gt;
              &lt;ITEM id='3'&gt;
                  &lt;Color&gt;Red&lt;/Color&gt;
                  &lt;Name&gt;Apple&lt;/Name&gt;
              &lt;/ITEM&gt;
          &lt;/FOOD&gt;
  </code></pre>
  
  <p>It creates a CSV but its empty &amp; I think its because of the print lines in the foreach loop.</p>
  
  <p>Any help would be greatly appreciated! </p>