如果我有以下示例 XML,如何使用 XML::Twig
从字段中提取 _Id
?
<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;
}
最佳答案
这是获得 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";
}
关于perl - 如何使用 XML::Twig 模块在 Perl 中提取属性/特性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26347838/