how to parse a simple xml file to a readable format

cjd143SD picture cjd143SD · Apr 20, 2011 · Viewed 14.5k times · Source

Perl newbie here. Can someone kindly show me how to use perl to extract data from this xml file and format the output anyway i would need? Would I use XML::Simple or open this as a fh and split it somehow? thank you.

Documentation for using XML::Simple doesn't seem simple to me.

For example I have a small xml file that looks like this.

test.xml

<?xml version="1.5" encoding="UTF-8"?><org.apache.Content duration="277135" count="51" numDirs="50" bytesUsed="110133451"/>

I would like to convert attribute="value" pairs to be readable like csv file, : or however, i want to print it out.

Ex:

duration:277135 count:51 numDirs:50 bytesUsed:110133451

Answer

Nikhil Jain picture Nikhil Jain · Apr 20, 2011
Use XML::Simple - Easy API to maintain XML (esp config files) or 
see XML::Twig - A perl module for processing huge XML documents in tree mode.

use strict;
use warnings;
use XML::Simple;
use Data::Dumper;

my $xml = q~<?xml version="1.5" encoding="UTF-8"?>
<org.apache.Content duration="277135" count="51" numDirs="50" bytesUsed="110133451"/>~;

print $xml,$/;

my $data = XMLin($xml);

print Dumper( $data );

foreach my $attributes (keys %{$data}){
  print"$attributes : ${$data}{$attributes}\n";
}

Output:

bytesUsed : 110133451
numDirs : 50
count : 51
duration : 277135