Search code examples
perlperl-modulexml-twigancestor

How to display ancestors with XML::Twig?


I do not know how to display the ancestors_or_self of one Element.

Here is the error message I get when using the method ancestors_or_self(): Can't call method "print" without a package or object reference at xxxx

#!/usr/bin/perl -w
use warnings;
use XML::Twig;

my $t= XML::Twig->new;
my $v= XML::Twig::Elt->new;

$v= $t->first_elt('[@id]');
$v->print;
print ("\n\n");
$v->ancestors_or_self->print;

thanks for your help on Perl XML::Twig


Solution

  • ancestors_or_self returns a list -- assuming you want the path to the element, you also want ->path not ->print. And as ->path returns the path you will have to do something like this:

    #!/usr/bin/perl -w
    use warnings;
    use XML::Twig;
    
    my $t= XML::Twig->new;
    my $v= XML::Twig::Elt->new;
    
    $v= $t->first_elt('[@id]');
    print $v->path . "\n";
    print ("\n\n");
    print $_->path . "\n" foreach $v->ancestors_or_self;