Wednesday, May 11, 2011

perl xml tidy examples

Method 1:

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



Method 2:


#!/usr/bin/perl
use strict;
use warnings;

my $doc;

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

# process file content with XML::Tiday
my $tidy_doc = XML::Tiday->new(xml => $doc);
$tidy_doc->tidy();
$tidy_doc->write("output.xml");


An alternative, which makes use of the LibXML module:
# create XML::LibXML::Document object
my $doc = $parser->parse_file("./test.xml");

# use the the toString fuction to extract the XML content from the object
my $tidy_doc = XML::Tiday->new(xml => $doc->toString);
$tidy_doc->tidy();
$tidy_doc->write("output.xml");



Method 3:


use warnings;
use strict;
use XML::Tidy;

my $doc = <<EOF;
<?xml version="1.0" encoding="utf-8"?>
<inode>
<perfdata collection="GigabitEthernet0/0">
<info cmd="show interface" detail="GigabitEthernet0/0">
<input_rate>show_interface_input_rate.tcl</input_rate>
<output_rate>show_interface_output_rate.tcl</output_rate>
</info>
<info cmd="show interface" detail="GigabitEthernet0/0/1">
<output_rate>show_interface_output_rate.tcl</output_rate>
</info>
</perfdata>
<perfdata collection="GigabitEthernet1/1">
<info cmd="show interface" detail="GigabitEthernet1/1">
<input_rate>show_interface_input_rate.tcl</input_rate>
<output_rate>show_interface_output_rate.tcl</output_rate>
</info>
<info cmd="show interface" detail="GigabitEthernet1/1/0">
<output_rate>show_interface_output_rate.tcl</output_rate>
</info>
</perfdata>
<perfdata collection="self">
<info cmd="show buffers summary" detail="">
<big_pool>show_buffers_summary_big_pool.tcl</big_pool>
<small_pool>show_buffers_summary_small_pool.tcl</small_pool>
</info>
</perfdata>
</inode>
EOF

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

No comments: