Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

XML::Twig how to find a parent's attribute

by slugger415 (Monk)
on Jul 25, 2014 at 17:53 UTC ( [id://1095074]=perlquestion: print w/replies, xml ) Need Help??

slugger415 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, quick question I couldn't find in the documentation (or didn't understand the syntax) for XML::Twig - how do I match a parent or ancestor's attribute? For instance, I have some XML:

<p conref="hello"> <ul> <li>Bob</li> <li>Mary</li> </ul> </p>

If I'm evaluating li elements, I want to know if one of its parents has a conref attribute set. What's the syntax for that?

$elt->parent();

... returns the parent, which would be ul in this case, but how do I match the ancestor that contains the attribute I'm looking for?

The doc says this about parent:

parent ($optional_condition)
Return the parent of the element, or the first ancestor matching the $optional_condition

Just not sure how to phrase the optional_condition here.

thanks, Scott

Replies are listed 'Best First'.
Re: XML::Twig how to find a parent's attribute
by AppleFritter (Vicar) on Jul 25, 2014 at 18:34 UTC
    Looking at XML::Twig's source, you can apparently pass subroutine references, regular expressions, or plain strings (which can themselves be used in various ways to express different things). Take a look at the _install_cond subroutine.
Re: XML::Twig how to find a parent's attribute
by poj (Abbot) on Jul 25, 2014 at 18:55 UTC
    $elt->parent('p[@conref != ""]') poj

      Thanks poj, though I should have mentioned, I won't always know that the ancestor is a p; it could be anything. Anyway to grab "whatever it is"?

        sub li { my ($t,$elt) = @_; my $e = $elt->parent('[@conref != ""]'); # p removed if ( defined $e ){ print $e->tag." ".$elt->text."\n"; } }
        poj

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1095074]
Approved by AppleFritter
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-03-29 06:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found