perl根据条件从xml文件解析特定值
问题描述:
有人可以告诉我如何从xml文件解析出特定信息吗?我想用正则表达式吗?perl根据条件从xml文件解析特定值
我正在使用XML::Simple
来查看我的test.xml文件。
例如,我要搜索的字符串test-out-00000
,如果它存在,那么给我/打印size
= 135860644
数据:
$VAR1 = {
'recursive' => 'no',
'version' => '0.20.202.1.1101050227',
'time' => '2011-09-30T02:49:39+0000',
'filter' => '.*',
'file' => {
'owner' => 'test_act',
'replication' => '3',
'blocksize' => '134217728',
'permission' => '-rw-------',
'path' => '/source/feeds/customer/test/test-out-00000',
'modified' => '2011-09-30T02:48:41+0000',
'size' => '135860644',
'group' => '',
'accesstime' => '2011-09-30T02:48:41+0000'
},
'path' => '/source/customer/test',
'directory' => {
'owner' => 'test_act',
'group' => '',
'permission' => 'drwx------',
'path' => '/source/feeds/customer/test',
'accesstime' => '1970-01-01T00:00:00+0000',
'modified' => '2011-09-30T02:48:41+0000'
},
'exclude' => ''
};
recursive:no
version:0.20.202.1.1101050227
time:2011-09-30T02:49:39+0000
filter:.*
file:HASH(0x84c841c)
path:/source/customer/test
directory:HASH(0x84c7648)
exclude:
工作perl脚本:
use strict;
use warnings;
use XML::Simple;
use Data::Dumper;
my $xml = $ARGV [0];
my $data = XMLin($xml);
print Dumper($data);
foreach my $attributes (keys %{$data}){
print"$attributes:${$data}{$attributes}\n";
}
XML文件test.xml:
<?xml version="1.0" encoding="UTF-8"?>
<listing time="2011-09-30T02:49:39+0000" recursive="no" path="/source/customer/test" exclude="" filter=".*" version="0.20.202.1.1101050227">
<directory path="/source/feeds/customer/test" modified="2011-09-30T02:48:41+0000" accesstime="1970-01-01T00:00:00+0000" permission="drwx------" owner="test_act" group=""/>
<file path="/source/feeds/customer/test/test-out-00000" modified="2011-09-30T02:48:41+0000" accesstime="2011-09-30T02:48:41+0000" size="135860644" replication="3" blocksize="134217728" permission="-rw-------" owner="test_act" group=""/>
</listing>
答
我假设你一直在寻找文件名中的文本字符串?如果是这样,这是做的一种方式:
use strict;
use warnings;
use XML::Simple;
my $xml = $ARGV [0];
my $data = XMLin($xml);
my $size = 0;
if (exists $data->{file}->{path} and $data->{file}->{path} =~ /test-out-00000/) {
$size = $data->{file}->{size};
}
如果您的数据格式如下,你也可以使用XML ::的libxml只获取使用XPath表达式的值。
谢谢。是的,我一直在寻找路径中的特定文件名。这对我有用。 – jdamae