in reply to XML::Twig correct parent, xpath filter

Can I just say how marvellous it is to see someone with use English; and then going on to use single letter variable names?

But for the sake of being more helpful - to match the _content_ of an element, you probably want the "string()" function in your XPath:

use strict; use warnings; use English; use XML::Twig; my $xmlFile = "demo.xml"; my $t = XML::Twig->new( pretty_print => 'indented_a', keep_atts_order => 1, twig_handlers => { q(myconfig/myobj[string(uniqueName)=" objA "]/myattributes/ +attribB) => \&getfoo, } ); $t->parse ( \*DATA ); $t->print; exit 0; sub getfoo { my ($t, $e) = @_; print "text=", $e->text(), "' tag='", $e->tag(), "' path='", $e->path(), "' parentTag='", $e->parent->tag(), "'\n"; } __DATA__ <myconfig> <myobj> <uniqueName> objA </uniqueName> <myattributes> <attribA> fooA </attribA> <attribB> fooB </attribB> </myattributes> </myobj> <myobj> <uniqueName> objB </uniqueName> <myattributes> <attribA> fooA </attribA> <attribB> fooB </attribB> </myattributes> </myobj> </myconfig>

Although actually I'd probably be suggesting not using twig_handlers or roots unless you've a need to keep memory footprint down, and just use "get_xpath" and "children" etc. to process it after parsing

foreach my $elt ( $t -> get_xpath( '//myconfig/myobj/uniqueName[string +()=" objA "]/../myattributes/attribB' ) ) { $elt -> print; }

Or just iterate all the "myobjs" and extract differentiating elements.

Replies are listed 'Best First'.
Re^2: XML::Twig correct parent, xpath filter
by dcbecker (Novice) on Oct 30, 2015 at 19:54 UTC
    that is exactly what I was looking for. much easier than trying to decode and look at all the elements. the real XML is far more complicated and bigger. Sorry about the single letter variables. was just trying to keep the example short. real version is better :-) Thanks to both of you.