| Processing XML with Perl | | Michel Rodriguez |
![]() Things to know about XML::Parser | | ![]() XML::Parser Styles |
Example: extracting information from an XML document
Print the winery of the cheapest wine in a class, using XML::Parser handlers:
#!/bin/perl -w
use strict;
use XML::Parser;
my( $class, $cheap_winery, $winery, $cheap_price, $price, $in_winery, $in_price);
my $parser= new XML::Parser(
Handlers => { Start => \&start,
End => \&end,
Char => \&char
});
$parser->parsefile( "wine.xml");
sub start
{ my( $expat, $element, %att)= @_;
if( $element eq "class")
{ $class= $att{name}; }
elsif( $element eq "winery")
{ $in_winery= 1; $winery= ""}
elsif( $element eq "price")
{ $in_price= 1; $price= ""}
}
sub char
{ my( $expat, $string)= @_;
if( $in_winery) { $winery .= $string; }
elsif( $in_price) { $price .= $string; }
}
sub end
{ my( $expat, $element)= @_;
if( $element eq "winery")
{ $in_winery= 0; }
elsif( $element eq "price")
{ if( !$cheap_price || ($price < $cheap_price) )
{ $cheap_winery= $winery;
$cheap_price= $price;
}
$in_price= 0;
}
elsif( $element eq "class")
{ print "$class: $cheap_winery (\$$cheap_price)\n";
$cheap_price=0;
}
}
|
![]() Things to know about XML::Parser | | ![]() XML::Parser Styles |


