Skip to content

Instantly share code, notes, and snippets.

@JJ
Created July 13, 2011 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JJ/1079899 to your computer and use it in GitHub Desktop.
Save JJ/1079899 to your computer and use it in GitHub Desktop.
Pretty-print XML files with user-specified colors and indents
?xml version="1.0"?>
<?xml-stylesheet href="tienda0.xsl" type="text/xsl"?>
<equipo>
<jugador posicion='portero'>Araña</jugador>
<jugador posicion='delantero'>Cazagoles</jugador>
</equipo>
#!/usr/bin/perl
use YAML qw(LoadFile);
use File::Slurp qw(read_file);
my $conf = shift || die "Falta fichero de configuracion\n\tUso: $0 configuracion.yaml fichero.xml\n";
my $fichero_xml = shift || die "Falta fichero\n\tUso: $0 configuracion.yaml fichero.xml\n";
my $defs = LoadFile($conf) || die "No puedo cargar $conf: $!\n";
my @colors = @{$defs->{'colors'}};
my %indents = %{$defs->{'indents'}};
my $page = read_file( $fichero_xml) || die "No puedo leer $fichero_xml: $!\n";
#Instrucciones
$page =~ s{<\?}{<font color='$colors[0]'>\&lt;\?}g;
$page =~ s{\?>}{\?\&gt;</font><br />}g;
#tags
for ( keys %indents ) {
my $indent = "&nbsp;"x$indents{$_}->[0];
my $color = $colors[$indents{$_}->[1]];
my $post = $indents{$_}->[2];
$page =~ s{<($_[^>]*)>}{$indent<font color="$color">\&lt;$1\&gt;</font>$post}g;
$page =~ s{</$_>}{$indent<font color="$color">\&lt;/$_\&gt;</font><br />}g;
}
print $page;
---
colors:
- red
- #993300
- blue
indents:
equipo:
- 0
- 1
- '<br />'
jugador:
- 2
- 2
@JJ
Copy link
Author

JJ commented Jul 13, 2011

If you need to pretty-print XML files for tutorials or presentations, this file can do the trick. It specifies first the colors you are going to use for every level from the root (red in this case) down, and then some specifics for each tag you might find: level of indentation, tree level (0 and 1 in the case of equipo) and suffix after start tag. To apply it, ./format-any.pl format.yaml file.xml

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment