问一个XML数据解析提取的问题

问一个XML数据解析提取的问题

问一个XML数据解析提取的问题
 (此贴内容已隐藏,限有过发贴记录的注册用户查看, 但您没有在中国Perl协会 用户推广组发表过任何帖子,将不能浏览本贴内容)
你给出的 XML 文件很多地方有错, 我假设你想解析的 XML 文件内容如下:[quote]<?xml version="1.0" encoding="UTF-8"?>
<documentinfo>
<documentname>0a02b280-66f0-11dc-4823-00585b200029.xml</documentname>
<measurements date="2007-09-19" time="12:30:40" measurementversion="9">
<leadmeasurements>
<leadmeasurement leadname="I">
<pamp>20</pamp>
<pump>30</pump>
</leadmeasurement>
<leadmeasurement leadname="II">
<pamp>20</pamp>
<pump>30</pump>
</leadmeasurement>
</leadmeasurements>
</measurements>
</documentinfo>
[/quote]
那么就算不知道 $data 的结构,使用 Data::Dumper 也很容易获知:[quote]#!/usr/bin/perl

use XML::Simple;
use Data::Dumper;

my $xml_name =<<XML ;
<?xml version="1.0" encoding="UTF-8"?>
<documentinfo>
<documentname>0a02b280-66f0-11dc-4823-00585b200029.xml</documentname>
<measurements date="2007-09-19" time="12:30:40" measurementversion="9">
<leadmeasurements>
<leadmeasurement leadname="I">
<pamp>20</pamp>
<pump>30</pump>
</leadmeasurement>
<leadmeasurement leadname="II">
<pamp>20</pamp>
<pump>30</pump>
</leadmeasurement>
</leadmeasurements>
</measurements>
</documentinfo>
XML
my $xml = new XML::Simple;
my $data = $xml->XMLin($xml_name);

print Dumper $data;
[/quote]
输出:[quote]$VAR1 = {
'measurements' => {
'measurementversion' => '9',
'leadmeasurements' => {
'leadmeasurement' => [
{
'pamp' => '20',
'pump' => '30',
'leadname' => 'I'
},
{
'pamp' => '20',
'pump' => '30',
'leadname' => 'II'
}
]
},
'time' => '12:30:40',
'date' => '2007-09-19'
},
'documentname' => '0a02b280-66f0-11dc-4823-00585b200029.xml'
};
[/quote]
因此,你可以这样取到各个pamp/pump值:[quote]for (@{ $data->{measurements}->{leadmeasurements}->{leadmeasurement} }){

print "leadname: ".$_->{leadname}." ",
"pamp: ".$_->{pamp}." ",
"pump: ".$_->{pump}."\n";

}
[/quote]

[url=http://search.cpan.org/~grantm/XML-Simple-2.18/lib/XML/Simple.pm]XML::Simple 的文档[/url]描述比较详细, 你可以读读