1

I have XML data that will be like this

<Root>
  <Bag Identifier="1">
    <Code Amount="0" Code="XA" Conversion="0" Currency="INR" Desc="" Id="1"/>
  </Bag>
  <Bag Identifier="2">
    <Code Amount="21" Code="XA" Conversion="0" Currency="INR" Desc="" Id="2"/>
  </Bag>
</Root>

I want to parse this and create a Perl hash as below. The Identifier attribute of each Bag element should be the primary hash key.

'2' => {
  'Amount' => "21",
  'Code' => "XA",
  'Currency' => "INR",
}
'1' => {
  'Amount' => "0",
  'Code' => "XA",
  'Currency' => "INR",
}

This is my Perl code

my $parser = XML::LibXML->new();
my $xml_doc = $parser->parse_string($response);

my $test_node = $xml_doc->findnodes('//Bag/');
print Dumper($test_node);

print $test_node->find('@Id')->string_value();

How can I create the hash that I have described?

2
  • Do you have a question? Commented Dec 6, 2014 at 6:31
  • yes i am not able to read the values and create the same hash structure Commented Dec 6, 2014 at 6:32

1 Answer 1

4

This program does as you ask. It reads a copy of your sample data from the DATA file handle, and uses Data::Dump to display the resultant data structure.

use strict;
use warnings;

use XML::LibXML;

my $data = XML::LibXML->load_xml(IO => \*DATA);

my %data;

my @bags = $data->findnodes('/Root/Bag');

for my $bag (@bags) {

  my $id = $bag->getAttribute('Identifier');

  my ($code) = $bag->getChildrenByTagName('Code');

  my %item;
  for my $attr (qw/ Amount Code Currency /) {
    $item{$attr} = $code->getAttribute($attr);
  }
  $data{$id} = \%item;
}

use Data::Dump;
dd \%data;

__DATA__
<Root>
  <Bag Identifier="1">
    <Code Amount="0" Code="XA" Conversion="0" Currency="INR" Desc="" Id="1"/>
  </Bag>
  <Bag Identifier="2">
    <Code Amount="21" Code="XA" Conversion="0" Currency="INR" Desc="" Id="2"/>
  </Bag>
</Root>

output

{
  1 => { Amount => 0, Code => "XA", Currency => "INR" },
  2 => { Amount => 21, Code => "XA", Currency => "INR" },
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.