perl 使用XML::Parser的Handler解析XML
来一个event-based的XML解析,其实Style的Stream方法就是一个event-based的XML解析。参考文献:http://search.cpan.org/~msergeant/XML-Parser-2.36/Parser.pm#HANDLERS
操纵文档:
# cat sample1
Partly Cloudy
12
6
#
perl脚本:
# cat sample4.pl
#!/usr/bin/perl -w
use strict;
use XML::Parser;
my $file = "sample1";
my $p = XML::Parser->new(Handlers => {Start => \&start,
End => \&end,
Char => \&char,});
my $text;
my @attr;
$p->parsefile($file);
sub start {
my ($p,$tag) = (shift,shift);
@attr = @_ if @_;
}
sub end {
my ($p,$tag) = @_;
if ($tag eq "OUTLOOK") {
print "OUTLOOK: $text\n";
}elsif ($tag eq "TEMPERATURE") {
print "$attr: $text $attr\n";
}
$text = '';
}
sub char {
my ($p,$str) = @_;
return unless $str =~ /\S/;
$str =~ s/^\s+//;
$str =~ s/\s+$//;
$text .= $str;
}
#
执行结果:
# perl sample4.pl
OUTLOOK: Partly Cloudy
MAX: 12 C
MIN: 6 C
这个方法不错,解析简单的XML很顺手。
页:
[1]