如何使用Perl的XML :: Twig从XML中提取子值?
发布时间:2020-12-16 06:28:49 所属栏目:大数据 来源:网络整理
导读:我正在解析 XML文件并尝试访问 XML文件中的值. #!/usr/bin/perl -wuse strict;use XML::Twig;my $file = 'files/camelids.xml';print "File :: $filen";my $twig = XML::Twig-new();$twig-parsefile($file);# print "twig :: $twign";my $root = $twig-roo
我正在解析
XML文件并尝试访问
XML文件中的值.
#!/usr/bin/perl -w use strict; use XML::Twig; my $file = 'files/camelids.xml'; print "File :: $filen"; my $twig = XML::Twig->new(); $twig->parsefile($file); # print "twig :: $twign"; my $root = $twig->root; # print "root :: $rootn"; my $num = $root->children('species'); print "num :: $numnnn"; 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. 如何解决这个问题? 这行代码是否有任何错误,需要进行任何修改(这里我试图将通用名称作为Bactrian Camel) print $root->children('species')->first_child_text('common-name'); 解决方法
将最后一行更改为
my @nums = $root->children('species'); print "num :: @numsnnn"; 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'); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |