Pretty Print XML with Perl

Let’s say you’ve got a file named “file.xml” and want it pretty printed, all indented nice and everything…

For just such an occasion I have a Perl script named “” and I just run my XML file through it like so: cat file.xml | perl

Here’s the code I use:


use XML::Twig;
use XML::Parser;

my $xml = XML::Twig->new(pretty_print => 'indented');



You can even pass it through right as it comes in over the wire: curl | perl

Here’s an example of data from Foursquare without pretty printing. (I used curl to grab the data. Also, I added in some line breaks, just to make it a little more readable.):

<?xml version="1.0" encoding="UTF-8"?>
<created>Mon, 09 Aug 10 00:50:33 +0000</created>
<name>The Kiltie</name><primarycategory><id>79067</id>
<fullpathname>Food:Ice Cream</fullpathname><nodename>Ice Cream</nodename>
<display>Pete P. @ The Kiltie</display></checkin></checkins>

And here’s the same data, again using curl to grab it, and then passing it through the script:

<?xml version="1.0" encoding="UTF-8"?>
    <created>Mon, 09 Aug 10 00:50:33 +0000</created>
      <name>The Kiltie</name>
        <fullpathname>Food:Ice Cream</fullpathname>
        <nodename>Ice Cream</nodename>
    <display>Pete P. @ The Kiltie</display>

I still find Perl extremely useful for this sort of task… I’m sure there are other command line ways to do this, but this one works for me.

(Hat tip to A Curious Programmer where I picked up this Perl code from…)