#!/usr/bin/env perl
use strict;
use warnings;
use XML::Parser;
my $parser = XML::Parser::->new(Handlers => {
Start => \&hdl_start,
End => \&hdl_end,
Char => \&hdl_char,
Default => \&hdl_def,
Final => \&hdl_final,
});
my @xml_files
= qw{./pm_xml_parser_test_file1.xml ./pm_xml_parser_test_file2.xml};
for (@xml_files) {
_init_handler_vars('filename');
get_value($_);
}
sub get_value {
my $file = shift;
my $returned = $parser->parsefile($file);
if (defined $returned) {
print "Wanted content: '$returned'\n";
}
else {
print "Wanted content not found!\n";
}
return;
}
# Private scope for handler variables
{
my ($wanted_element, $in_wanted_element,
$wanted_content, $found_wanted_content);
sub _init_handler_vars {
$wanted_element = shift;
$in_wanted_element = 0;
$wanted_content = '';
$found_wanted_content = 0;
return;
}
sub hdl_start {
my ($expat, $element, $attr, @vals) = @_;
if ($element eq $wanted_element) {
$in_wanted_element = 1;
}
return;
}
sub hdl_end {
my ($expat, $element) = @_;
if ($element eq $wanted_element) {
$in_wanted_element = 0;
}
return;
}
sub hdl_char {
my ($expat, $string) = @_;
if ($in_wanted_element) {
if ($string) {
$found_wanted_content = 1;
$wanted_content = $string;
}
}
return;
}
sub hdl_def {
my ($expat, $string) = @_;
# Default handler actions here
return;
}
sub hdl_final {
my ($expat) = @_;
return unless $found_wanted_content;
return $wanted_content;
}
}
####
$ cat ./pm_xml_parser_test_file1.xml
pm_xml_parser_test_file1.xml
$ cat ./pm_xml_parser_test_file2.xml
pm_xml_parser_test_file2.xml
####
$ pm_xml_parser_test.pl
Wanted content: 'pm_xml_parser_test_file1.xml'
Wanted content: 'pm_xml_parser_test_file2.xml'