XML::Simple - How to fix that the same xml structure results in 2 different Perl data structures, depending on amount of members/syblings?

StackOverflow https://stackoverflow.com/questions/15625961

Question

I am new to XML::Simple (and also not very keen in xml). I want to use it for parsing a simple xml structure that I get as result of an API. I do not have any influence on the xml I get.

When the returned xml list contains just one member I have a complete different perl data structure as when the list has more members. This is very annoying.

I'd like to have the data structure as in example 2 even if the result only contains one member.

What do I have to do to get identical output?

Example 1:

#!/usr/bin/perl -w

use strict;
use warnings;
use Data::Dumper;
use XML::Simple;

my $xml1  = new XML::Simple;
my $data1 = $xml1->XMLin( '
<aaa>
    <bbb>
        <id>1</id>
        <text>Test 1</text>
    </bbb>
</aaa>
' );

print Dumper($data1);

Result 1:

$VAR1 = {
          'bbb' => {
                   'text' => 'Test 1',
                   'id' => '1'
                 }
        };

Example 2:

my $xml2  = new XML::Simple;
my $data2 = $xml2->XMLin( '
<aaa>
    <bbb>
        <id>1</id>
        <text>Test 1</text>
    </bbb>
    <bbb>
        <id>2</id>
        <text>Test 2</text>
    </bbb>
</aaa>
' );

print Dumper($data2);

Result 2:

$VAR1 = {
          'bbb' => {
                   '1' => {
                          'text' => 'Test 1'
                        },
                   '2' => {
                          'text' => 'Test 2'
                        }
                 }
        };

Tnx for your help.

Cheers, Robert

Was it helpful?

Solution

Try doing this :

#!/usr/bin/perl -w

use strict;
use warnings;
use Data::Dumper;
use XML::Simple;

my $xml1  = new XML::Simple;
my $data1 = $xml1->XMLin( '
    <aaa>
        <bbb>
            <id>1</id>
            <text>Test 1</text>
        </bbb>
    </aaa>
    ',
    ForceArray=>['bbb']
);

print Dumper($data1);

From perldoc XML::Simple :

ForceArray => 1 # in - important
This option should be set to '1' to force nested elements to be represented as arrays even when there is only one.

This option is especially useful if the data structure is likely to be written back out as XML and the default behaviour of rolling single nested elements up into attributes is not desirable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top