来一个event-based的XML解析,其实Style的Stream方法就是一个event-based的XML解析。

参考文献:http://search.cpan.org/~msergeant/XML-Parser-2.36/Parser.pm#HANDLERS

操纵文档:

[root@dou xml]# cat sample1
<FORECAST>
  <OUTLOOK>
    Partly Cloudy
  </OUTLOOK>
  <TEMPERATURE TYPE="MAX" DEGREES="C">12</TEMPERATURE>
  <TEMPERATURE TYPE="MIN" DEGREES="C">6</TEMPERATURE>
</FORECAST>
[root@dou xml]#
 

perl脚本:

[root@dou xml]# 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[1]: $text $attr[3]\n";
        }
        $text = '';
}
sub char {
        my ($p,$str) = @_;
        return unless $str =~ /\S/;
        $str =~ s/^\s+//;
        $str =~ s/\s+$//;
        $text .= $str;
}
[root@dou xml]#
 

执行结果:

[root@dou xml]# perl sample4.pl
OUTLOOK: Partly Cloudy
MAX: 12 C
MIN: 6 C
 

这个方法不错,解析简单的XML很顺手。