[Solved] How do I create an XML file (in a specific location), containing a given hash? [closed]


XML::Simple is abysmal, especially for generating XML.


You said the format should be the following:

<keys>
   <key1><value1></value1></key1>
   [...]
</keys>

That format doesn’t make much sense. The solution below produces XML in the following format:

<elements>
   <element><key>key1</key><value>value1</value></element>
   [...]
</elements>

Solution:

use XML::Writer qw( );

open(my $fh, '>', $qfn)
   or die("Can't create \"$qfn\": $!\n");

my $writer = XML::Writer->new(OUTPUT => $fh);
$writer->xmlDecl();
$writer->startTag("elements");
for my $key (sort keys(%hash)) {
   $writer->startTag("element");
   $writer->dataElement("key", $key);
   $writer->dataElement("value", $hash{$key});
   $writer->endTag("element");
}
$writer->endTag("keys");
$writer->end();

The following is a terser format:

<elements>
   <element key="key1">value1</element>
   [...]
</elements>

Solution:

use XML::Writer qw( );

open(my $fh, '>', $qfn)
   or die("Can't create \"$qfn\": $!\n");

my $writer = XML::Writer->new(OUTPUT => $fh);
$writer->xmlDecl();
$writer->startTag("elements");
for my $key (sort keys(%hash)) {
   $writer->dataElement("element", $hash{$key}, key => $key);
}
$writer->endTag("keys");
$writer->end();

Adjust at will.

1

solved How do I create an XML file (in a specific location), containing a given hash? [closed]