如何使用XML :: Twig模块在Perl中提取属性/属性?

时间:2014-10-13 19:51:17

标签: perl xml-twig

如果我有以下示例XML,如何使用_Id从字段中提取XML::Twig

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

我尝试过以下的组合而没有运气。

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;
}

1 个答案:

答案 0 :(得分:4)

这是获取100的一种方法。它使用first_child方法:

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";
}