在 Twig 中打印 XML 的内容
Printing content of XML in Twig
我试图在 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( '//sentence')
此外,使用 $root->att( 'id')
或 $root->id
,因为 $root->{att}->{id}
不是官方 API 的一部分,将来可能会发生变化。
我试图在 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( '//sentence')
此外,使用 $root->att( 'id')
或 $root->id
,因为 $root->{att}->{id}
不是官方 API 的一部分,将来可能会发生变化。