如何使用Perl';从XML中提取子值;s XML::细枝?
我正在解析XML文件并尝试访问XML文件中的值如何使用Perl';从XML中提取子值;s XML::细枝?,xml,perl,xml-twig,Xml,Perl,Xml Twig,我正在解析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; # pr
#!/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>
如何解决这个问题
这行代码中是否有任何错误以及需要进行的任何修改(这里我试图将通用名称
作为双峰驼
)
将最后一行更改为
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');
}
my @nums = $root->children('species');
print "num :: @nums\n\n\n";
foreach my $num (@nums) {
print $num->first_child_text('common-name');
}
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');
}
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();