我正在尝试将一些 XML 解析为 Perl,但测试并没有产生我所期望的结果。
$buffer = qq[<DeliveryReport><message id="msgID" sentdate="xxxxx" donedate="xxxxx" status="xxxxxx" gsmerror="0" /></DeliveryReport>];
$xml = XML::Simple->new( ForceArray => 1 );
$file = $xml->XMLin($buffer) or die "Failed for $reply: $!\n";
use Data::Dumper;
print Dumper($file);
$msgid = $file->{message}->{id};
$message_status = $file->{message}->{status};
print "OUTPUT: $msgid $message_status";
但是输出是空白的,并且print Dumper
id 属性看起来是错误的,但我不知道为什么。
$VAR1 = {
'message' => {
'msgID' => {
'status' => 'xxxxxx',
'gsmerror' => '0',
'sentdate' => 'xxxxx',
'donedate' => 'xxxxx'
}
}
};
输出:
这是正常工作的最终代码。
use XML::Simple;
use Data::Dumper;
$xml = XML::Simple->new (KeyAttr=>'',ForceArray => 1);
$file = $xml->XMLin('
<DeliveryReport>
<message id="msgID1" sentdate="xxxxx" donedate="xxxxx" status="xxxxxx" gsmerror="0" />
<message id="msgID2" sentdate="yyy" donedate="yyy" status="yyy" gsmerror="0" />
</DeliveryReport>
') or die "Failed for $reply: $!\n";
print Dumper($file);
$numOfMsgs = @{$file->{message}};
print "<br /><br />I've received $numOfMsgs records<br />";
for($i = 0; $i < $numOfMsgs; $i++) {
$msgid = $file->{message}->[$i]->{id};
$message_status = $file->{message}->[$i]->{status};
print "message id: [$msgid]<br />";
print "status id: [$message_status]<br />";
print "<br />";
}