在Twig中打印XML的内容

前端之家收集整理的这篇文章主要介绍了在Twig中打印XML的内容前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在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;

我也尝试过经常提出的文本,但是我得到了同样的错误.我在这里错过了什么?

解决方法

这不是jQuery; – (你必须遍历后代列表.

另外你不能使用print来收集变量中的数据,你使用print来打印!使用sprint代替:

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

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

此外,使用$root-> att(‘id’)或$root-> id,因为$root-> {att} – > {id}不是官方API的一部分,并且可能会更改未来.

猜你在找的XML相关文章