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

When you use twig_roots, the matching nodes don't see their parents. Try using twig_handlers instead.
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: XML::Twig correct parent, xpath filter
by dcbecker (Novice) on Oct 30, 2015 at 15:34 UTC

    thanks. that solved the problem with the missing parents. I still have the problem with how to select on a specific node. I'm still getting two nodes recognized. I did correct one typo with the object name, and I no longer get a parsing error, but I still cant figure out how to select the specific myobj that I'm looking for. modified example (got rid of spaces in demo.xml uniqueName node, and added the '@' in front of uniqueName in the handler filter.

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

    output:

    text= fooB ' tag='attribB' path='/myconfig/myobj/myattributes/attribB' + parentTag='myattributes' text= fooB ' tag='attribB' path='/myconfig/myobj/myattributes/attribB' + parentTag='myattributes' <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>
      @ is for attributes. Remove the whole predicate, Twig doesn't understand it anyway. Just extract the uniqueName element, compare it to the wanted id, and change the element:
      #!/usr/bin/perl use warnings; use strict; use XML::Twig; my $xmlFile = 'demo.xml'; my $t = XML::Twig->new( keep_atts_order => 1, pretty_print => 'indented_a', twig_handlers => { 'myconfig/myobj/myattributes/attribB' => \ +&getfoo, }, ); $t->parsefile($xmlFile); $t->print; sub getfoo { my ($t, $e) = @_; my $id = $e->parent->parent->first_child_text('uniqueName'); if ('objB' eq $id) { $e->set_text(' NEW '); } }

      For comparison, the same task in XML::XSH2:

      open demo.xml ; set /myconfig/myobj[uniqueName='objB']/myattributes/attribB 'NEW' ; save :b ;
      لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ