XML::Simple options for XMLout

October 23rd, 2005 by Rohan

The other day I had the need of converting a hash structure to XML format. The XML::Simple CPAN module is the best tool for this. However there are some options you need to be aware of to get your XML the way you want. The default options for the XMLout function may leave you confused and bothered.

Lets say you have a simple hash structure like this:

$href = {
'CD' => {
'Audio' => {
'Title' => 'Money For Nothing',
'Artist' => 'Dire Straits',
},
},
};

Now go ahead and use the XMLout function like this:

use XML::Simple;
my $xml = XMLout($href);
print "$xml\n";

Here is what you get:

<opt>
  <CD name="Audio" Artist="Dire Straits" Title="Money For Nothing" />
</opt>

Yeah! You need to go through the docs to find the right options. Firstly, what can be seen is that all the elements are lined up as attributes of the root “CD” element. Assuming, you don’t want this (I didn’t), you can make use of the NoAttr option. Like this:

$xml = XMLout(
        $href,
        NoAttr => 1,
);
print "$xml\n";

And this is what we get:

<opt>
  <CD>
    <name>Audio</name>
    <Artist>Dire Straits</Artist>
    <Title>Money For Nothing</Title>
  </CD>
</opt>

Much Better!

However, we still have that that irritating “<name>Audio</name>” string coming up. It turns out that XML::Simple uses a default value for the KeyAttr option of which name is one of them. Hence you see that “<name>Audio</name>” thing. You can turn this off, by setting the KeyAttr value to an empty list. At the same time lets get rid of the root element which by default is opt. Do this by setting the RootName option to an undef value.

Ok. Now lets check it out.

$xml = XMLout(
        $href,
        NoAttr => 1,
        KeyAttr => [],
        RootName => undef,
);
print "$xml\n";

Here is the output:

<CD>
    <Audio>
      <Artist>Dire Straits</Artist>
      <Title>Money For Nothing</Title>
    </Audio>
</CD>

Much, Much Better! Of course, assuming this is the way you intended your XML to look like.

[Post to Twitter] Tweet This Post  [Post to Facebook] Facebook 

One Response to “XML::Simple options for XMLout”

  1. dikr61 Says:

    Hi Rohan, thank you for this compact and helpful statement. I think, I will be crazy with the XMLout output without your help - thanks

Leave a Reply




Tweet This Post links powered by Tweet This v1.4.1, a WordPress plugin for Twitter.