Bram Vanroy
Bram Vanroy

Reputation: 28437

Printing content of XML in Twig

I am trying to print some basic logs in Perl but I get stuck on a very simple issue: I cannot print the contents of XML tags.

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";
}

I tried tthe code above but I receive the error

Can't call method "print" without a package or object reference at file.pl line 35, line 15.

Which is this line:

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

I also tried text as is often proposed, but I get the same error. What am I missing here?

Upvotes: 4

Views: 777

Answers (1)

mirod
mirod

Reputation: 16161

This is not jQuery ;--( You have to iterate through the list of descendants.

Plus you can't use print to collect data in a variable, you use print to... print! Use sprint instead:

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

If what you want is the text of the elements, and the contents of all sentence elements is pure text, you could also use $sentence= $root->findvalue( '//sentence')

Also, use $root->att( 'id'), or $root->id since $root->{att}->{id} is not part of the official API, and could potentially change in the future.

Upvotes: 3

Related Questions