在Twig中打印XML的内容

问题描述:

我想在Perl中打印一些基本日志,但遇到一个非常简单的问题:我无法打印XML标签的内容。在Twig中打印XML的内容

my $twig=XML::Twig->new(pretty_print => "nice"); 
$twig->parse($xml); 
my $root = $twig->root; 

my @desc=$root->descendants_or_self('node'); 
my [email protected]; 

my $sentence = $root->descendants('sentence')->print; 
my $sentenceid = $root->{att}->{id}; 

if ($nrofdesc > $maxdescendants) { 
    print "$sentence\t$nrofdesc\t$sentenceid\n"; 
} 

我尝试了上述里边反代码,但我收到错误

不能调用方法“打印”而不会在 file.pl线35的包装或对象引用,线15

这是这一行:

my $sentence = $root->descendants('sentence')->print; 

我也试过text经常提出,但我得到同样的错误。我在这里错过了什么?

+2

根据perldoc“后代”会给你一个列表,而不是一个对象。可能你需要通过印刷单个“树枝”的列表。 – eballes

这不是jQuery的; - 。(你有过后代的列表迭代

另外,您不能使用print在变量收集数据,您使用print至...打印使用! sprint代替:

$sentence= join '', map { $_->sprint } $root->descendants('sentence'); 

如果你想要的是元素的文字,并且所有sentence元素的内容是纯文本,您还可以使用$sentence= $root->findvalue('//sentence')

此外,使用$root->att('id')$root->id,因为$root->{att}->{id}不是官方API的一部分,未来可能会发生变化。

+0

但我知道一个先验,每根只会有一个'sentence'元素。那么,为什么我不能从列表中访问这个项目呢?但我想我应该用sprint来对待它,但你说得对。编辑;不,我真的需要'文字'。 –

+1

如果你知道只有一个句子,或者你只对第一个句子感兴趣,那么使用'$ root-> first_descendant('句子')'或甚至$ twig-> first_elt('句子')' – mirod

+0

酷! (我删除了我的答案,以便我可以接受你的答案。)问题:当试图在'$ root'上使用'first_elt'时,我得到*无法通过包“XML :: Twig :: Elt”找到对象方法“first_elt”* 。但是,当它在树枝上使用它的作品。怎么样? –