1

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 Answers 3

4

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";
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi John, for print "$key => $value \n" i get the output notification => ARRAY(0xb4227d0) , where notification is the element assumed as c1,c2,c3 etc.... What does this mean...?
ARRAY? I can see HASH, but not an array. If you get a list of hashes it's because those nodes have childnodes or no "text" data.
3

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
}

Comments

0

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.

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.