| Refresh | Home EGTry.com


use strict;
use XML::Parser;

my $parser=new XML::Parser (
  Handlers=> {
    Start => \&Start,
    End => \&End,
    Char => \&Char,
    Default => \&Default,
  });

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


$parser->parse($xml);

sub Start {
  my ($p, $elemName, %atts)=@_;
  print "<$elemName";
  foreach my $key (keys %atts) {
    print " $key=\"$atts{$key}\"";
  }  
  print ">\n";
}

sub End {
  my ($p, $elemName)=@_;
  print "</$elemName>\n";
}

sub Char {
  my ($p, $content)=@_;
  return  unless $content =~ /\S+/;
  print "$content\n";
}

sub Default {
  my ($p, $content)=@_;
}



Output

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