Search code examples
perlxml-twig

How do I extract an attribute/property in Perl using XML::Twig module?


If I have the below sample XML, how do I extract the _Id from the field using XML::Twig?

<note>
    <to _Id="100">Share</to>
    <from>Jane</from>
    <heading>Reminder</heading>
    <body>A simple text</body>
</note>

I've tried combinations of the below with no luck.

sub getId {
    my ($twig, $mod) = @_;

    ##my $to_id = $mod->field('to')->{'_Id'};  ## does not work
    ##my $to_id = $mod->{'atts'}->{_Id};       ## does not work
    ##my $to_id = $mod->id;                    ## does not work

    $twig->purge;
}

Solution

  • This is one way to get 100. It uses the first_child method:

    use warnings;
    use strict;
    use XML::Twig;
    
    my $xml = <<XML;
    <note>
        <to _Id="100">Share</to>
        <from>Jane</from>
        <heading>Reminder</heading>
        <body>A simple text</body>
    </note>
    XML
    
    my $twig = XML::Twig->new(twig_handlers => { note => \&getId });
    $twig->parse($xml);
    
    sub getId {
        my ($twig, $mod) = @_;
        my $to_id = $mod->first_child('to')->att('_Id');
        print "$to_id \n";
    }