January 09, 2012
Convert a Perl Hash of Hashes into XML with XML::Dumper
Posted by: gdelmatto : Category: Perl, Programming
For a project of mine, I wanted to convert a Perl data structure, a so called Hash of Hashes, into an XML.
The simple solution to this is to use the XML::Dumper module.
Let’s suppose your data structure looks like this:
%hash_of_hashes = {
item1 => {
item1_1 => 'value1_1',
item1_2 => 'value1_2',
},
item2 => {
item2_1 => 'value2_1',
item2_2 => 'value2_2',
},
};
You can easily convert this into an XML representation using this command:
my $xml_output = XML::Dumper::pl2xml( \%hash_of_hashes );
So you’ll end up with this output:
<perldata> <hashref memory_address="0x878e784"> <item key="item1"> <hashref memory_address="0x87a8c58"> <item key="item1_1">value1_1</item> <item key="item1_2">value1_2</item> </hashref> </item> <item key="item2"> <hashref memory_address="0x87a8c61"> <item key="item2_1">value2_1</item> <item key="item2_2">value2_2</item> </hashref> </item> </hashref> </perldata>
But be aware: You need to pass the hash by reference, imposing the \%hash_of_hashes notation, otherwise you end up with something like this:
<perldata> <scalar>item_1</scalar> <scalar>item_2</scalar> </perldata>
It’s so obvious, but I had overlooked that as well in the first attempts 😉
