Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Parsing XML

by davorg (Chancellor)
on Jun 23, 2000 at 15:03 UTC ( #19564=snippet: print w/ replies, xml ) Need Help??

Description:

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";
  }
}
Comment on Parsing XML
Download Code

Back to Snippets Section

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://19564]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2014-11-27 22:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (188 votes), past polls