| Refresh | Home EGTry.com

perl parse xml using SAX api



package MyHandler;

use strict;
use Data::Dumper;
sub new {
  my $class=shift;
  my $self={};
  bless $self, $class;
  return $self;
}

sub start_element {
  my $self=shift;
  my $hashref=shift;
  my $name=$hashref->{"Name"};
  my $attrs=$hashref->{"Attributes"};
  print "<$name"; 
  foreach my $key (keys %$attrs) {
    my $Name=$attrs->{$key}{"Name"};
    my $Value=$attrs->{$key}{"Value"};
    print " $Name=\"$Value\"";   
  }
  print ">\n";
}

sub end_element {
  my $self=shift;
  my $hashref=shift;
  my $name=$hashref->{"Name"};
  print "</$name>\n";
}

sub characters {
  my $self=shift;
  my $hashref=shift;
  my $data=$hashref->{"Data"};
  return unless $data =~ /\S/;
  if ($data eq ">" or $data eq "<" or $data eq "\"" or $data) {
    print $data;
  } else {
    print "$data\n";
  }
}

package main;

use XML::SAX;

my $p=XML::SAX::ParserFactory->parser(
  Handler => MyHandler->new
);

my $xml=<<'_end';
<book title="my first book">
 <chapter title="chapter 1" hasdownload="1">
<Hello>this is a simple xml document
this is the second line.
The last line
 </chapter>
</book>
_end

$p->parse_string($xml);
#p->parse_file(\*IN);


Output

<book title="my first book">
<chapter hasdownload="1" title="chapter 1">
<Hello>this is a simple xml document
this is the second line.
The last line
 </chapter>
</book>