XML::Simple
is a pain because you're never sure whether you need an array or a hash, and it is hard to distinguish between elements and attributes.
I suggest you make a move to XML::API
. This program demonstrates some how it would be used to create the same XML data as your own program that uses XML::Simple
.
It has an advantage because it builds a data structure in memory that properly represents the XML. Data can be added linearly, like this, or you can store bookmarks within the structure and go back and add information to nodes created previously.
This code adds the two book
elements in different ways. The first is the standard way, where the element is opened, the name
and value
elements are added, and the book
element is closed again. The second shows the _ast
(abstract syntax tree) method that allows you to pass data in nested arrays similar to those in XML::Simple
for conciseness. This structure requires you to prefix attribute names with a hyphen -
to distinguish them from element names.
use strict;
use warnings;
use XML::API;
my $xml = XML::API->new;
$xml->library_open;
$xml->book_open;
$xml->name('createdDate');
$xml->value('20141205');
$xml->book_close;
$xml->_ast(book => [
name => 'deletionDate',
value => '20111205',
]);
$xml->library_close;
print $xml;
output
<?xml version="1.0" encoding="UTF-8" ?>
<library>
<book>
<name>createdDate</name>
<value>20141205</value>
</book>
<book>
<name>deletionDate</name>
<value>20111205</value>
</book>
</library>