XML :: Parser打印单个属性值

时间:2014-10-02 16:59:59

标签: xml perl xml-parsing

我正在解析XML文件,该文件包含这样的节点。

<product id="12345" model="dvd" section="cmp" img="junk.jpg"></product>

这是我的代码。我需要为所有产品打印id属性的值。

use XML::Parser;
my $parser = XML::Parser->new( Handlers => { Start => \&handle_start } );
$parser->parsefile('D:\Project\mob.xml');

sub handle_start {
    my ( $expat, $element, %attrs ) = @_;
    if ( $element eq 'product' ) {
        print $element;
    }
}

1 个答案:

答案 0 :(得分:3)

由于id哈希中有%attrs,您只需要打印它:

sub handle_start {
    my ( $expat, $element, %attrs ) = @_;
    if ( $element eq 'product' ) {
        print $attrs{id}, "\n";
    }
}

XML::Parser是一个低级解析器。如果您考虑使用更复杂的API,请尝试XML::Twig

use warnings;
use strict;
use XML::Twig;

my $xml = <<XML;
<product id="12345" model="dvd" section="cmp" img="junk.jpg"></product>
XML

my $twig = XML::Twig->new(
    twig_handlers => { product => sub { print $_->att('id'), "\n" } },
);
$twig->parse($xml);
相关问题