1
votes

I am a perl newbie and i need help in parsing xml using perl.

Consider the following as my xml file

<A>
    <B1>
    </B1>
    <B2>
    </B2>
    <B3>
        <c1>
        </c1>
        <c2>
        </c2>
        <c3>
        </c3>

    </B3>
</A>

I need to extract the element B3 alone along with it's child nodes.

I am using XML:Simple to parse the xml file.

How to parse the element B3 alone into a variable so that I can use foreach to extract the child nodes.....?

Thanks in advance...!!

3

3 Answers

4
votes

XML::Simple will create a hash object, you may then loop over the hash. Just keep in mind, nested nodes will also be hash objects.

#!/usr/bin/perl
use XML::Simple;
#use Data::Dumper; # Not necessary 

$xml = new XML::Simple;

$data = $xml->XMLin('test.xml');


$b3 = $data->{B3};

while ( my ($key, $value) = each(%$b3) ) {
    print "$key => $value\n";
}
3
votes

You can figure these kinds of things easily, by doing:

perl -MData::Dumper -MXML::Simple -e 'print Dumper XMLin("-")' < /tmp/file.xml

Doing so, you see that you can:

use XML::Simple;
my $xml = XMLin("/tmp/file.xml");
my $b3_node = $xml->{B3};

while ( my ($c_key, $c_node) = each %$b3_node ) {
    ... do your stuff here
}
0
votes

If you are getting an array as your result, then the first-level nodes probably have the same tag; something like

<A>
  <B>
    B1 data  
  </B>
  <B>
    B2 data
  </B>
  <B>
    B2 data
  </B>
</A>

for which you could access the data as $data->{B}[0], $data->{B}[1], and $data->{B}[2].

If you need more help with your specific problem you will have to post the actual data, or something very close.