How can I extract child values from XML with Perl's XML::Twig?
Asked Answered
W

2

5

I am parsing the XML file and trying to access the values in XML file.

#!/usr/bin/perl -w

use strict;
use XML::Twig;

my $file = 'files/camelids.xml';
print "File :: $file\n";
my $twig = XML::Twig->new();

$twig->parsefile($file);
# print "twig :: $twig\n";

my $root = $twig->root;
# print "root :: $root\n";

my $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 to 500 kg.</mass>
      <appearance>
          <in-appearance>
              <inside-appearance>This is 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 a package or object reference at xml-twig_read.pl line 19.

How to fix this issue?

Is there anything wrong in this line of code and any modification needed (here I am trying to get the common-name as Bactrian Camel)

print $root->children('species')->first_child_text('common-name');
Workable answered 22/9, 2010 at 5:33 Comment(0)
S
6

Change the last lines to

my @nums = $root->children('species');
print "num :: @nums\n\n\n";

foreach my $num (@nums) {
print $num->first_child_text('common-name');
}

children returns an array, so you need to run over it.

To help debugging, try this:

my @nums = $root->children('species');
use Data::Dumper; #More debug information like this than a normal print
print Dumper @nums;

foreach my $num (@nums) {
print $num->first_child_text('common-name');
}
Schrick answered 22/9, 2010 at 6:39 Comment(0)
D
2
use XML::Twig;

my $file = 't2.xml';

print "File :: $file\n";
# exit();
my $twig = XML::Twig->new();

$twig->parsefile($file);
# print "twig :: $twig\n";

my $root = $twig->root;
# print "root :: $root\n";

my @nums = $root->children('species');
*print "num :: " . @nums . "\n\n\n";*

foreach my $num (@nums){
   print $num->first_child_text('common-name') . *"\n";*
}
#exit();
Dorser answered 11/9, 2011 at 18:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.