#!/Perl
#
use XML::Parser::PerlSAX;
my $file = "camelids01.xml";

my $handler = CamelHandler->new();
my $parser = XML::Parser::PerlSAX->new(Handler => $handler);

$parser->parse(Source => { SystemId => $file});

package CamelHandler;

use strict;

sub new {
    my $type = shift;
    return bless {}, $type;
}

my $current_element = '';
my $latin_name = '';
my $common_name = '';

sub start_element {
    my ($self, $element) = @_;

    my %attrs = %{$element->{Attributes}};
    $current_element = $element->{Name};

    if ($current_element eq 'species') {
        $latin_name = $element->{Attributes}->{'name'};
    }
    elsif ($current_element eq 'conservation') {
        print $common_name .' (' . $latin_name .') '
        .  $element->{Attributes}->{'status'} . "\n";
    }
}

sub end_element {
    my ($self, $element) = @_;

    if ($element->{LocalName} eq 'species') {
        $common_name = undef;
        $latin_name  = undef;
    }
}

sub characters {
    my ($self, $characters) = @_;
    my $text = $characters->{Data};
    $text =~ s/^\s*//;
    $text =~ s/\s*$//;
    return '' unless $text;

    if ($current_element eq 'common-name') {
        $common_name = $text;
    }
}

1;

