我有一个名为Logs的文件夹,其中包含多个文件夹Run 1,Run 1(1),Run 2(2)等。每个文件夹都包含一个plist文件,我需要解析它。但是我无法打开文件。我正在运行以下代码:
my $count = 0;
my $path = "Logs/";
for my $file (glob("${path}*/*Results.plist")) {
# initialize parser object and find insances of Fail
my $xp = XML::XPath->new(filename=>$file);
my @nodeset = $xp->find('/dict/array/dict/string[1]');
foreach my $element (@nodeset){
if ($element->string_value == "Fail") {
$count++;
}
}
}
print $count;
编辑:现在我需要在“string”子节点中查找“Fail”。 plist文件有4个失败,但我当前的代码只返回2.任何想法为什么?
plist文件的结构很简单:
<plist version="1.0">
<dict>
<key>All Samples</key>
<array>
<dict>
<key>LogType</key>
<string>Fail</string>
<key>Message</key>
<string>Text</string>
<key>Timestamp</key>
<date>2012-10-17T08:01:51Z</date>
<key>Type</key>
<integer>4</integer>
</dict>
<dict>
<key>LogType</key>
<string>Fail</string>
<key>Message</key>
<string>An error occurred while trying to run the script.</string>
<key>Timestamp</key>
<date>2012-10-17T08:20:46Z</date>
<key>Type</key>
<integer>7</integer>
</dict>
<dict>
<key>LogType</key>
<string>Pass</string>
<key>Message</key>
<string></string>
<key>Timestamp</key>
<date>2012-10-17T08:01:51Z</date>
<key>Type</key>
<integer>5</integer>
</dict>
</array>
</dict>
</plist>
答案 0 :(得分:2)
试试这个:
use strict; use warnings;
use XML::XPath;
my $path="Logs/";
my $count = 0;
for my $file (glob("${path}*/*Results.plist")){
my $xp = XML::XPath->new(filename => $file);
my $nodeset = $xp->find('/plist/dict/array/dict/string[1]/text()');
foreach my $node ($nodeset->get_nodelist) {
$count++ if XML::XPath::XMLParser::as_string($node) eq "Fail";
}
}
print $count;
答案 1 :(得分:2)
您的代码有几个问题:
以下是它的外观:
my $nodeset = $xp->find('/plist/dict/array/dict/string[1]');
foreach my $element ($nodeset->get_nodelist) {
if ($element->string_value eq "Fail") {
$count++;
}
}
PS:另外,我建议使用“使用警告;使用严格;”在你的代码中。