Velu Subramanian
Velu Subramanian

Reputation: 47

XML::Parser print single attribute value

I'm parsing a XML file and the file has nodes like this.

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

Here is my code. I need to print the value of id attribute for all products.

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

Upvotes: 1

Views: 169

Answers (1)

toolic
toolic

Reputation: 62236

Since you have the id in the %attrs hash, you just need to print it:

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

XML::Parser is a low-level parser. If you would consider using one with a more sophisticated API, try 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);

Upvotes: 3

Related Questions