我一直在试图弄清楚如何让一个XML数据源解析成一个CSV文件,这让我有点疯狂。我有一个数据源,我需要解析一个创建CSV。我还需要能够将节点ID包含在列中。以下是我有:Perl XML到CSV解析
#!/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循环中的打印线的。
任何帮助将不胜感激!
作为样式,不要将文件名硬编码到脚本中,如果可以避免的话。使它们成为可选参数,从'<>'(或者做等效)读取输入并将输出写入到'STDOUT'使得脚本更容易重用,组合和测试。 – reinierpost