我试图在 Perl 中打印一些基本日志,但我遇到了一个非常简单的问题:我无法打印 XML 标记的内容。
my $twig=XML::Twig->new(pretty_print => "nice");
$twig->parse($xml);
my $root = $twig->root;
my @desc=$root->descendants_or_self('node');
my $nrofdesc=@desc;
my $sentence = $root->descendants('sentence')->print;
my $sentenceid = $root->{att}->{id};
if ($nrofdesc > $maxdescendants) {
print "$sentence\t$nrofdesc\t$sentenceid\n";
}
我试过上面的代码但是我收到错误
Can't call method "print" without a package or object reference at file.pl line 35, line 15.
这是哪一行:
my $sentence = $root->descendants('sentence')->print;
我也尝试了通常建议的text
,但我得到了同样的错误。我在这里缺少什么?
最佳答案
这不是 jQuery ;--( 您必须遍历后代列表。
此外,您不能使用 print
来收集变量中的数据,您可以使用 print
来……打印!使用 sprint
代替:
$sentence= join '', map { $_->sprint } $root->descendants('sentence');
如果你想要的是元素的文本,而所有sentence
元素的内容都是纯文本,你也可以使用$sentence= $root->findvalue('//句子')
此外,使用 $root->att( 'id')
,或 $root->id
因为 $root->{att}-> {id}
不是官方 API 的一部分,将来可能会发生变化。
关于xml - 在 Twig 中打印 XML 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36788661/