How can I extract child values from XML with Perl's XML::Twig? -


i parsing xml file , trying access values in xml file.

#!/usr/bin/perl -w  use strict; use xml::twig;  $file = 'files/camelids.xml'; print "file :: $file\n"; $twig = xml::twig->new();  $twig->parsefile($file); # print "twig :: $twig\n";  $root = $twig->root; # print "root :: $root\n";  $num = $root->children('species'); print "num :: $num\n\n\n";  print $root->children('species')->first_child_text('common-name'); 

sample xml file is:

<?xml version="1.0"?> <camelids>   <species name="camelus bactrianus">     <common-name>bactrian camel</common-name>     <physical-characteristics>       <mass>450 500 kg.</mass>       <appearance>           <in-appearance>               <inside-appearance>this in inside appearance</inside-appearance>           </in-appearance>         </appearance>     </physical-characteristics>   </species> </camelids> 

output is:

file :: files/camelids.xml num :: 1   can't call method "first_child_text" without package or object reference @ xml-twig_read.pl line 19. 

how fix issue?

is there wrong in line of code , modification needed (here trying common-name bactrian camel)

print $root->children('species')->first_child_text('common-name'); 

change last lines to

my @nums = $root->children('species'); print "num :: @nums\n\n\n";  foreach $num (@nums) { print $num->first_child_text('common-name'); } 

children returns array, need run on it.

to debugging, try this:

my @nums = $root->children('species'); use data::dumper; #more debug information normal print print dumper @nums;  foreach $num (@nums) { print $num->first_child_text('common-name'); } 

Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -