Thursday, December 16, 2010

Day 16: pretty printing XML with XML::Twig

Today's entry is about XML::Twig. It can do serveral things, all related to parsing (and processing) XML documents.

XML::Twig can read an XML document all at once and build a tree structure. It can process it chunk by chunk or act like a filter. I want to show its usage as a XML pretty printer:
#!/usr/bin/perl

use warnings;
use strict;

use XML::Twig;

# XMLRPC-Request
my $xml = <<'END';
Test
test
END

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

$twig->print;

Which will produce the following output:
<?xml version="1.0"?>
<methodCall>
  <methodName>Test</methodName>
  <params>
    <param>
      <value>
        <string>test</string>
      </value>
    </param>
  </params>
</methodCall>

XML::Twig comes with a few command line utilities. One of them (xml_pp) is a XML pretty printer.

For more 'traditional' usage (parsing XML and extracting information) look at the documentation or brian d foy's blog entry.


Links:

No comments:

Post a Comment