Script
Use indentxml file.xml
para ver, indentxml file.xml > new.xml
para editar.
Onde indentxml é
#!/usr/bin/perl
#
# Purpose: Read an XML file and indent it for ease of reading
# Author: RedGrittyBrick 2011.
# Licence: Creative Commons Attribution-ShareAlike 3.0 Unported License
#
use strict;
use warnings;
my $filename = $ARGV[0];
die "Usage: $0 filename\n" unless $filename;
open my $fh , '<', $filename
or die "Can't read '$filename' because $!\n";
my $xml = '';
while (<$fh>) { $xml .= $_; }
close $fh;
$xml =~ s|>[\n\s]+<|><|gs; # remove superfluous whitespace
$xml =~ s|><|>\n<|gs; # split line at consecutive tags
my $indent = 0;
for my $line (split /\n/, $xml) {
if ($line =~ m|^</|) { $indent--; }
print ' 'x$indent, $line, "\n";
if ($line =~ m|^<[^/\?]|) { $indent++; } # indent after <foo
if ($line =~ m|^<[^/][^>]*>[^<]*</|) { $indent--; } # but not <foo>..</foo>
if ($line =~ m|^<[^/][^>]*/>|) { $indent--; } # and not <foo/>
}
Analisador
Naturalmente, a resposta canônica é usar um analisador XML adequado.
# cat line.xml
<a><b>Bee</b><c>Sea</c><d><e>Eeeh!</e></d></a>
# perl -MXML::LibXML -e 'print XML::LibXML->new->parse_file("line.xml")->toString(1)'
<?xml version="1.0"?>
<a>
<b>Bee</b>
<c>Sea</c>
<d>
<e>Eeeh!</e>
</d>
</a>
Utilitário
Mas talvez o mais fácil seja
# xmllint --format line.xml
<?xml version="1.0"?>
<a>
<b>Bee</b>
<c>Sea</c>
<d>
<e>Eeeh!</e>
</d>
</a>