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

标签 perl xml-twig

如果我有以下示例 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/

相关文章:

mysql - 像 £(英镑)这样的拉丁字符编码在使用 perl 脚本编码后会抛出垃圾值

regex - 如何正确设置正则表达式以用 perl 替换多行变量占位符

xml - 如何使用 Perl 使用 TWIG 提取 CDATA 内容

xml - 将编码后的标签保留在 XML::Twig 中

perl - 在 Win32 Perl 中使用 XML::Twig 字符串损坏和不可打印字符

xml - Perl 中 XML::Twig 的性能调优和优化

html - 修复带有双引号的 HTML 属性值

mysql - 如何将带引号的字符串插入到 Perl DBI 查询中?

arrays - Perl:强制按数字顺序散列

perl - 仅当键没有值时如何删除哈希键?