http://www.perlmonks.org?node_id=19564

Here's a short demo of parsing XML using the Tree mode of XML::Parser. It works on any well-formed XML document and prints out a representation of the documents structure, e.g. given the file

<FORECAST> <OUTLOOK> Partly Cloudy </OUTLOOK> <TEMPERATURE TYPE="MAX" DEGREES="C">12</TEMPERATURE> <TEMPERATURE TYPE="MIN" DEGREES="C">6</TEMPERATURE> </FORECAST>

it will display:

FORECAST [] OUTLOOK [] Partly Cloudy TEMPERATURE [DEGREES: C, TYPE: MAX] 12 TEMPERATURE [DEGREES: C, TYPE: MIN] 6
use strict; use XML::Parser; my $p = XML::Parser->new(Style => 'Tree'); my $doc = $p->parsefile(shift); my $level = 0; process_node(@$doc); sub process_node { my ($type, $content) = @_; my $ind = ' ' x $level; if ($type) { my $attrs = shift @$content; print $ind, $type, ' ['; print join(', ', map { "$_: $attrs->{$_}" } keys %{$attrs}); print "]\n"; ++$level; while (my @node = splice(@$content, 0, 2)) { process_node(@node); } --$level; } else { $content =~ s/\n/ /; $content =~ s/^\s+//; $content =~ s/\s+$//; print $ind, $content, "\n"; } }