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

In reply to Parsing XML by davorg

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.