2010-09-22 74 views
5

我解析XML文件並嘗試訪問XML文件中的值。如何使用Perl的XML :: Twig從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. 

如何解決這個問題?

這有什麼錯在這行代碼,並

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

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

孩子的回報需要(在這裏我想獲得common-nameBactrian Camel

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

回答

6

更改的最後幾行任何修改一個數組,所以你需要運行它。

爲了幫助調試,試試這個:

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'); 
} 
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();