Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl XML::Parser - howto access a simple parsed tree?

Tags:

parsing

xml

perl

I want to parse a simple string using XML::Parser. This works fine. But I do not know how to access the result.

#!/usr/bin/perl

use Data::Dumper;
use XML::Parser;

my $parser = XML::Parser->new( Style => 'Tree' );
my $tree   = $parser->parse( '<xml type="test" Id="ca19cfd5" result="1 test 2 test 3" elapsed="9" Size="12345" />' );

print Dumper( $tree );

shows me

$VAR1 = [
'xml',
[
{
'Size' => '12345',
'Id' => 'ca19cfd5',
'type' => 'test',
'elapsed' => '9',
'result' => '1 test 2 test 3'
 }
 ]
 ];

So it perfectly could parse my string. But how do I access these fields? Something like "my $result = $tree..."

The given xml string will always have the same syntax like shown above. Only the content differs.

Tnx in advance, Enkidu

like image 735
Enkidu Avatar asked Nov 04 '25 10:11

Enkidu


1 Answers

The attributes you are looking for are in $tree->[1]->[0]

my $atts= $tree->[1]->[0];

then

print "size: $atts->{Size}\n";

That said XML::Parser is not the easiest module to use, it's a bit too low-level. XML::Twig or XML::LibXML will give you what you want more easily.

like image 128
mirod Avatar answered Nov 06 '25 04:11

mirod