Wednesday, May 11, 2011

How to Format XML in Perl Using XML::Tidy


Method 1: Direct File Parsing

This is the most straightforward approach. It passes the filename directly to the XML::Tidy constructor, formats it, and writes the changes.

Perl
my $tidy_doc = XML::Tidy->new("filename" => "/Users/.../tidy.xml");
$tidy_doc->tidy();
$tidy_doc->write(); 


Method 2: Slurping the File into a Variable

This method reads the entire XML file into a scalar variable first before passing it to XML::Tidy.

Perl
#!/usr/bin/perl
use strict;
use warnings;
use XML::Tidy; # Corrected from the page's typo 'XML::Tiday'

my $doc;

# Use an anonymous code block to limit the scope of the IRS unset
{
    # Unset IRS (input record separator) to read the whole file at once
    local $/ = undef;
    
    # Open and read the entire file into a scalar variable
    open my $fh, "<", "./test.xml" or die "Could not open file: $!";
    $doc = <$fh>;
    close $fh;
}

# Process file content 
my $tidy_doc = XML::Tidy->new(xml => $doc);
$tidy_doc->tidy();
$tidy_doc->write("output.xml");
Note: The page also shows an alternative for Method 2 that uses the XML::LibXML module to parse the document first, and then passes $doc->toString into XML::Tidy.

Method 3: Using an Inline Here-Doc String

If you have the XML data generated directly within your script, you can load it as a string using a "Here-Doc" (<<EOF) $doc="<<EOF;" <?xml ? XML::Tidy; ```perl a and before encoding="utf-8" file. it my outputting strict; tidy to up use version="1.0" warnings;>

my $tidy_doc = XML::Tidy->new(xml => $doc);
$tidy_doc->tidy();
$tidy_doc->write('out.xml');

No comments: