用XML::Simple解析xml文件

2011-02-16  李卓华 

xml文件
<?xml version="1.0"?>
<customer-data>
<customer>
<first_name>Frank</first_name>
<last_name>Sanbeans</last_name>
<dob>3/10</dob>
<email>frank@example.com</email>
<vehicle>Volvo S60</vehicle>
<vehicle>Honda Accord</vehicle>
</customer>
<customer>
<first_name>Sandy</first_name>
<last_name>Sanbeans</last_name>
<dob>4/15</dob>
<email>sandy@example.com</email>
<vehicle>McLaren MP4-20</vehicle>
<vehicle>Chevrolet S-10</vehicle>
</customer>
</customer-data>

perl:
#!/usr/bin/perl
use strict;
use XML::Simple;
use Data::Dumper;
my $xml = XMLin('xml_example2.xml',forcearray=>1);
foreach my $customer (@{$xml->{customer}}) {
print "Name: $customer->{first_name}->[0] ";
print "$customer->{last_name}->[0]\n";
print "Birthday: $customer->{dob}->[0]\n";
print "E-mail Address: $customer->{email}->[0]\n";
print "Vehicle(s): @{$customer->{vehicle}}\n";
}

print Dumper($xml);

my $xml = XMLin('./xml_example2.xml',forcearray=> [ 'vehicle' ]);
foreach my $customer (@{$xml->{customer}}) {
print "Name: $customer->{first_name} ";
print "$customer->{last_name}\n";
print "Birthday: $customer->{dob}\n";
print "E-mail Address: $customer->{email}\n";
print "Vehicle(s): @{$customer->{vehicle}}\n";
}

print Dumper($xml);

my $xml = XMLin('xml_example2.xml');
print Dumper($xml);


my $xml = XMLin('./xml_example2.xml',forcearray=> [ 'vehicle' ],KeyAttr=>[
'email' ]
);
print Dumper($xml);

278°/2786 人阅读/0 条评论 发表评论

登录 后发表评论