This page was exported from phaq [ http://phaq.phunsites.net ]
Export date: Tue Jun 18 5:05:24 2019 / +0000 GMT
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 ;-)
Powered by [ Universal Post Manager ] plugin. HTML saving format developed by gVectors Team www.gVectors.com