Gopal
Gopal

Reputation: 797

how to convert xml to hash and retrieve the values from it

I have simple xml for which dumper is getting generated, I need to convert the xml to hash, I am using XML::Simple package, how can I able to achieve it. basically I need to get the value from hash like {var1}{server1}{servername}

use XML::Simple;
use Data::Dumper;
my $filename="config.xml";
open(my $fh,'<:encoding(UTF-8)',$filename)
or die "could not open the file:$filename";
my $ref = XMLin($xml, ForceArray => 1);
print Dumper($ref);

output

$VAR1 = {
      'server2' => [
                   {
                     'servername' => [
                                     'ICE'
                                   ],
                     'user' => [
                               'csftplc1'
                             ],
                     'ipaddress' => [
                                    '199.53.9.51'
                                  ]
                   }
                 ],
      'server1' => [
                   {
                     'servername' => [
                                     'DMZ '
                                   ],
                     'user' => [
                               'csftplch'
                             ],
                     'ipaddress' => [
                                    '199.53.9.50'
                                  ]
                   }
                 ],
      'id_name' => '317D'
    };

config.xml

<?xml version="1.0" encoding="UTF-8"?>
<job id_name="317D">
<server1>
        <servername>DMZ </servername>
        <ipaddress>199.53.9.50</ipaddress>
        <user>csftplch</user>
</server1>
<server2>
        <servername>ICE</servername>
        <ipaddress>199.53.9.51</ipaddress>
        <user>csftplc1</user>
</server2>
</job>

Upvotes: 1

Views: 3387

Answers (2)

Borodin
Borodin

Reputation: 126742

If you remove the ForceArray option and use the default settings then XML::Simple will do what you ask. However you should use something other than XML::Simple for new code as it has many problems

use strict;
use warnings;

use XML::Simple;

my $ref = XMLin(\*DATA);

print $ref->{server1}{servername}, "\n";
print $ref->{server2}{servername}, "\n";


__DATA__
<?xml version="1.0" encoding="UTF-8"?>
<job id_name="317D">
<server1>
        <servername>DMZ </servername>
        <ipaddress>199.53.9.50</ipaddress>
        <user>csftplch</user>
</server1>
<server2>
        <servername>ICE</servername>
        <ipaddress>199.53.9.51</ipaddress>
        <user>csftplc1</user>
</server2>
</job>

output

DMZ 
ICE

Upvotes: 3

choroba
choroba

Reputation: 241938

As the Dumper output shows, ForceArray created some arrays on the way.

my $name = $ref->{server1}[0]{servername}[0];

That's one of the reasons why even the documentation of XML::Simple warns against itself.

Upvotes: 2

Related Questions