Perl解析XML文件,可以调用XML::Simple模块。安装命令:
use XML::Simple;
$xml=new XML::Simple;
$path='E:\\surefire-reports';
opendir(DIR,$path);
@filename=readdir(DIR);
for($i=2;$i<@filename;$i++)
{
#print "$path\\@filename[$i]";
if(@filename[$i]=~m/.xml/){
$myfile="$path\\@filename[$i]";
$data=$xml->XMLin($myfile);
if(($data->{'errors'}!='0')||($data->{'failures'}!='0')){
print "\nname: $data->{'name'} tests: $data->{'tests'} failures: $data->{'failures'} errors: $data->{'errors'} ";
print "\nerror message: $data->{'testcase'}->{'error'}->{'message'}";
print "\n";
}
}
}
closedir(DIR);
说明:
- 之所以$i是从2开始,是因为readdir方法还会输出“.”和“..”,代表当前目录和父目录。但这并不是我们所关注的文件名,故不做考虑。
- “@filename[$i]=~m/.xml/”用正则表达式过滤出后缀名为xml的文件,参见http://www.chinaunix.net/jh/25/159388.html
- XMLin方法是读取XML文件,若要写一个XML文件,则用XMLout方法
- 关于调试,可以use Data::Dumper;通过print Dumper($data);查看xml结构
待解析的文件格式:
<?xml version="1.0" encoding="UTF-8" ?>
<testsuite failures="0" time="204.04" errors="1" skipped="0" tests="1" name="wrong_oldpasswordTest">
<properties>
<property name="java.runtime.name" value="Java(TM) SE Runtime Environment"/>
<property name="sun.boot.library.path" value="C:\Program Files\Java\jdk1.6.0_20\jre\bin"/>
</properties>
<testcase time="202.48" classname="wicresoft.wrong_oldpasswordTest" name="wrongoldpassword">
<error message="ERROR: Element OldPassword not found" type="com.thoughtworks.selenium.SeleniumException">com.thoughtworks.selenium.SeleniumException: ERROR: Element OldPassword not found at com.thoughtworks.selenium.HttpCommandProcessor.throwAssertionFailureExceptionOrError(HttpCommandProcessor.java:97)
at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:91)
</error>
<system-out>@SLTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 6.953 sec @SLRunning wicresoft.wrong_oldpasswordTest
</system-out>
</testcase>
</testsuite>
运行:
在命令行中,输入“perl test.pl >>d:\123.txt",即将解析结果写入到D盘的123.txt文件中。