ikegami has covered the hash -> XML case quite nicely. I wish to offer an alternative suggestion - don't, use JSON
instead. XML
is quite powerful and complicated, but it's really designed as a document format - think how HTML does things - you have tags, attributes and content.
For a significant number of use cases, you're better off with JSON
instead - it's a simpler format of hashes and arrays. As a result, it more directly reflects the perl data types.
So you can do:
#!/usr/bin/env perl
use strict;
use warnings;
use JSON;
my %stuff = ( key => "value",
another_key => "another_value",
some_tags => [ "tag1", "tag2", "tag3" ] );
print to_json ( \%stuff, { pretty => 1 } );
This gives you:
{
"key" : "value",
"another_key" : "another_value",
"some_tags" : [
"tag1",
"tag2",
"tag3"
]
}
Or collapses it onto one line if you just to_json ( \%stuff );
:
{"another_key":"another_value","key":"value","some_tags":["tag1","tag2","tag3"]}
Reading it back in is as simple as:
my $json_str = to_json ( \%stuff );
my $json_object = from_json ( $json_str );
print Dumper \$json_object;
If all you need is hashes and arrays (and can do without XML attributes, xpath
, XSLT
processing) then this may be a better fit - I suggest it, because you indicate that you want to export a simple hash.
But in either case - don't use XML::Simple
- it isn't simple at all.