5

我正在解析 XML 文件并尝试访问 XML 文件中的值。

#!/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');

示例 XML 文件是:

<?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>

输出是:

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.

如何解决这个问题?

这行代码有什么问题吗?需要进行任何修改(这里我试图获取common-nameas Bactrian Camel

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

2 回答 2

6

将最后几行更改为

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

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

children 返回一个数组,因此您需要遍历它。

为了帮助调试,试试这个:

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');
}
于 2010-09-22T06:39:08.540 回答
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();
于 2011-09-11T18:57:38.073 回答