我一直在试图弄清楚如何将 xml 数据源解析为 CSV 文件,这让我有点抓狂。我有一个数据源,我需要解析并创建一个 CSV。我还需要能够将节点 ID 作为一列包含在内。这是我所拥有的:
#!/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>
它创建了一个 CSV,但它是空的,我认为这是因为 foreach 循环中的打印行。
任何帮助将不胜感激!