我正在尝试使用 perl 和 XML::Simple 从 XML 文件中提取少量数据到 csv 文件中。
这是数据的编辑版本:
<?xml version="1.0" encoding="UTF-8"?>
<orders xmlns="http://www.demandware.com/xml/impex/order/2006-10-31">
<order order-no="W100148941">
<order-date>2011-08-22T16:15:47.000Z</order-date>
<custom-attributes>
<custom-attribute attribute-id="basket_notes">bnotes974211</custom-attribute>
<custom-attribute attribute-id="omOrderID">974211</custom-attribute>
</custom-attributes>
</order>
</orders>
使用这个脚本:
#!/usr/bin/perl
use XML::Simple;
use Data::Dumper;
$xml = new XML::Simple;
$data = $xml->XMLin("$ARGV[0]", ForceArray=>1);
print Dumper($data);
foreach $o (@{$data->{order}}) {
print "$ARGV[1]", ",";
print "$ARGV[2]", ",";
print "$ARGV[3]", ",";
print "$ARGV[4]", ",";
print $o->{"order-no"}, ",";
print $o->{"order-date"}, ",";
foreach my $o ( @{ $data->{'custom-attribute'} } ) {
print 'in level 1';
foreach my $attr ( @{ $data->{'custom-attribute'} } ) {
print 'in level 2';
if ( $attr->{'attribute-id'} eq 'basket_notes' ) {
print '"', $data->{'content'}, '"', ",";
}
}
}
print "\n";
}
得到我这个输出:
,,,,W100148941,ARRAY(0x7f7f63a524c0),
不使用 ForceArray 选项 XMLin 会将上面的 ARRAY(...) 替换为正确的值,但不适用于只有一个数据元素的文件,而且很明显,此代码永远不会进入自定义属性数组打印任何东西。
我究竟做错了什么?
更新:
将上面的循环代码更改为:
foreach $o (@{$data->{order}})
{
print "$ARGV[1]", ",";
print "$ARGV[2]", ",";
print "$ARGV[3]", ",";
print "$ARGV[4]", ",";
print $o->{"order-no"}, ",";
#print $o->{"order-date"}, ",";
print $o->{"order-date"}->[0], ",";
foreach my $o ( @{ $data->{'custom-attributes'} } ) {
print 'in level 1';
foreach my $attr ( @{ $o->{'custom-attribute'} } ) {
print 'in level 2';
if ( $attr->{'attribute-id'} eq 'omOrderID' ) {
print '"', $data->{'content'}, '"', ",";
}
}
}
print "\n";
}
产生这个:
,,,,W100148941,2011-08-22T16:15:47.000Z,
看起来代码只是没有进入自定义属性循环,我不知道为什么。