Wednesday, October 18, 2006

Perl: XML Parsing program in Perl using XML module

Here is a sample code snippet on how we can easily parse an XML doc in PERL (tested in Linux).


#!usr/local/bin/perl

##Programs for XML parsing.

use XML::Parser;

my $p = XML::Parser->new(Style => "Tree");
my $input = '/home/ammishra/perl/ip.xml';


traverse( $p->parsefile( $input ) );
exit(0);


sub traverse
{
my $node = shift;
while ( defined ( my $element = shift @{ $node } ))
{
my $child = shift @{ $node };
if ( ref $child ) # if $child is yet another arrayref node
{
my %attr = %{ shift @{ $child } };
# yank the attributes out of the grandchild
print "$element has attributes @{[ %attr ]}\n";
traverse( $child );
# child element is now just a list of element/children pairs
}
else # otherwise, if $child is just some text
{
print "$child\n";
}
}
}

No comments:

Post a Comment