3

Input file :SN.xml

<?xml version='1.0'?>
<root>
<category cname='Cname1' id='c1'>
  <subcat key='3' sname='Subname1' sid='sid1'>
    <prod key='1' pname='Productname'>value1</prod>
  </subcat>
</category>
</root>

I am using these code for converting XML file to hash.

my $config = XML::Simple->new();
$config = XMLin('SN.xml');
print Dumper($config);

I'm getting below output :

'3' => {
          'sid' => 'sid1',
              'sname' => 'Subname1',
                   'prod' => {
                               'content' => 'value1',
                               'pname' => 'Productname',
                               'key' => '1'
                                                   }
        },

I am expecting to get output below, please help me to get this..

  '3' => {
             'sid' => 'sid1',
                     'sname' => 'Subname1',
                                       'prod' => {
                                                 '1' => {
                                                        'pname' => 'Productname',
                                                        'content' =>'value1'
                                                      },
                                                 }
             },

Please suggest me any other module producing this result too..

Thanks in Advance!

Vasanth
  • 201
  • 1
  • 12
  • 2
    Your XML is not valid! Maybe it's a typo? Line #4 you close a tag `` that was never opened. – psxls Nov 15 '13 at 07:19
  • Thanks psxls! This not a error,i corrected it. I want ouput which i mentioned above format. – Vasanth Nov 15 '13 at 07:38
  • The line `my $config = XML::Simple->new();` is useless here. You don't use the created `XML::Simple` object at all. – Slaven Rezic Nov 15 '13 at 08:34

1 Answers1

4
my $xs = XML::Simple->new( ForceArray => 1 );
my $config = $xs->XMLin('SN.xml');
print Dumper $config;

The ForceArray option will force nested elements to be put in arrayrefs even if there is only one nested element. This allows the default KeyAttr option to kick in and recognise your 'key' attributes.

stevenl
  • 6,736
  • 26
  • 33