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:
#!/usr/bin/perl
use warnings;
use strict;
use XML::XPath;
#Name of the CSV File
my $filename = "parse.csv";
#Create the file.
open(INPUT,">$filename") or die "Cannot create file";
#Collect the XML and set nodes
my($xp) = XML::XPath->new( join('', <DATA>) );
my(@records) = $xp->findnodes( '/CATALOG/CD' );
my($firstTime) = 0;
#Loop through each record
foreach my $record ( @records ) {
my(@fields) = $xp->find( './child::*', $record )->get_nodelist();
unless ( $firstTime++ ) {
#Print Headers
print( join( ',', map { $_->getName() } @fields ), "\n");
}
#Print Content
print( join( ',', map { $_->string_value() } @fields ), "\n");
}
#Close the file.
close(INPUT);
__DATA__
<FOOD>
<ITEM id='1'>
<Color>Brown</Color>
<Name>Steak</Name>
</ITEM>
<ITEM id='2'>
<Color>Blue</Color>
<Name>Blueberries</Name>
</ITEM>
<ITEM id='3'>
<Color>Red</Color>
<Name>Apple</Name>
</ITEM>
</FOOD>
It creates a CSV but its empty & I think its because of the print lines in the foreach loop.
Any help would be greatly appreciated!
<>(or doing the equivalent) and writing output toSTDOUTmakes your scripts much easier to reuse, combine and test.