XMLParser.pl

 
 1  #!/usr/bin/perl -w
 2
 3  use XML::Parser;
 4
 5  undef $/;
 6  $xml=<>;
 7
 8  $tab=0;
 9  $tab_char="\t";
10  sub handle_start{
11          shift;
12          my$element=shift;
13          print "\n","$tab_char"x$tab;
14          my$attributes="";
15          while(@_){
16                  my$key=shift;
17                  my$val=shift;
18                  $attributes.=" $key=\"$val\"";
19          }
20          print "<$element$attributes>";
21          my$ref={element=>$element,count=>0};
22          if($prev=pop @stack){
23                  $prev->{count}++;
24                  push @stack,$prev;
25          }
26          push @stack,$ref;
27          $tab++;
28  }
29  sub handle_end{
30          my$element=$_[1];
31          $tab--;
32
33          my$ref=pop @stack;
34          my$c=$ref->{count};
35          print "\n","$tab_char"x$tab if $c;
36          print "</$element>";
37  }
38  sub handle_char{
39          my$char=$_[1];
40          print "$char";
41  }
42
43  $p2 = new XML::Parser(Handlers => {Start => \&handle_start,
44                  End   => \&handle_end,
45                  Char  => \&handle_char});
46
47  $p2->parse($xml);