#!/usr/bin/env perl # prettyxml - pretty-print XML # Andrew Ho (andrewgho@google.com) use warnings; use strict; use XML::Parser (); use vars qw($COLUMNS $INDENT); $COLUMNS = 80; $INDENT = ' '; use vars qw($Output $Column $Indent $Text); my $p = XML::Parser->new( Handlers => { Init => \&Init, Start => \&Start, End => \&End, Char => \&Default, Default => \&Default, Final => \&Final, } ); my $output = undef; eval { binmode STDOUT, 'encoding(UTF-8)'; $output = @ARGV ? $p->parsefile(shift) : $p->parse(*STDIN); }; if($@) { print $Output, "\n"; die $@; } elsif(defined $output) { print $output, "\n"; } else { print $Output, "\n"; } exit 0; sub Init { $Indent = 0; $Column = 0; $Output = ''; undef $Text; } sub Start { my($expat, $element, @pairs) = @_; $Output .= "\n"; $Output .= $INDENT x $Indent if $Indent > 0; $Output .= '<' . $element; if(@pairs) { $Output .= ' ' . $pairs[2 * $_] . '="' . $pairs[1 + (2 * $_)] . '"' foreach 0 .. int($#pairs / 2); } $Output .= ">"; $Indent++; $Column = $Indent; undef $Text; } sub End { my($expat, $element) = @_; $Indent--; $Output .= "\n" unless defined $Text; $Output .= $INDENT x $Indent if ($Indent > 0) && (!defined $Text); $Output .= ''; $Column = $Indent; undef $Text; } sub Default { my($expat, $str) = @_; if(defined $str && $str !~ /^\s*$/sm) { $Output .= $str; $Text = 1; } else { undef $Text; } } sub Final { $Output =~ s/^\s+//; $Output =~ s/\s+$//; return $Output; }