Question

I am having trouble building what i think is a hashref (href) in perl with XML::Simple. I am new to this so not sure how to go about it and i cant find much to build this href with arrays. All the examples i have found are for normal href.

The code bellow outputs the right xml bit, but i am really struggling on how to add more to this href

Thanks Dario

use XML::Simple;
$test = {
book => [
    {
        'name' => ['createdDate'],
        'value' => [20141205]
    },
        {
        'name' => ['deletionDate'],
        'value' => [20111205]
    },

]

};
$test ->{book=> [{'name'=> ['name'],'value'=>['Lord of the rings']}]};
print XMLout($test,RootName=>'library');
Was it helpful?

Solution

To add a new hash to the arrary-ref 'books', you need to cast the array-ref to an array and then push on to it. @{ $test->{book} } casts the array-ref into an array.

push @{ $test->{book} }, { name => ['name'], value => ['The Hobbit'] };

OTHER TIPS

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top