我的目标是start_tag_handler
(见下文)在找到/标记时获取apps
/title
内容(见下面的示例 XML)。apps
title
并
在找到/标记时end_tag_handler
获取apps
/logs
内容。apps
logs
但相反,此代码返回 null 并退出。
这是用于解析的 Perl 代码(使用XML::Twig)###:
#!/usr/local/bin/perl -w
use XML::Twig;
my $twig = XML::Twig->new(
start_tag_handlers =>
{ 'apps/title' => \&kicks
},
twig_roots =>
{ 'apps' => \&app
},
end_tag_handlers =>
{ 'apps/logs' => \&bye
}
);
$twig -> parsefile( "doc.xml");
sub kicks {
my ($twig, $elt) = @_;
print "---kicks--- \n";
print $elt -> text;
print " \n";
}
sub app {
my ($twig, $apps) = @_;
print "---app--- \n";
print $apps -> text;
print " \n";
}
sub bye {
my ($twig, $elt) = @_;
print "bye \n";
print $elt->text;
print " \n";
}
这是 doc.xml###:
<?xml version="1.0" encoding="UTF-8"?>
<auto>
<apps>
<title>watch</title>
<commands>set,start,00:00,alart,end</commands>
<logs>csv</logs>
</apps>
<apps>
<title>machine</title>
<commands>down,select,vol_100,check,line,end</commands>
<logs>dump</logs>
</apps>
</auto>
这是控制台中的输出###:
C:\>perl parse.pl
---kicks---
---app---
watchset,start,00:00,alart,endcsv
---kicks---
---app---
machinedown,select,vol_100,check,line,enddump