in reply to Twig delete not deleting the entire section?
indeed as wise monks above (choroba and poj) already said the (sub)tree is not parsed (never realized this fact btw) in the moment you catch <name>name1</name> if instead you put your logic on the site element it works as you expect, just doing $_->delete if $_->children ('name[string() =~ /name2/]');
use strict; use warnings; use XML::Twig; my $xml = q( <sites> <site siteid="ONE"> <name>name1</name> <address>address1</address> <contact>contact1</contact> </site> <site siteid="TWO"> <name>name2</name> <address>address2</address> <contact>contact2</contact> </site> </sites> ); my %handlers = ( site => sub { # my ($twig, $cnt) = @_; # $cnt is unuseful: iirc $_ is mapped +$_[1] $_->delete if $_->children ('name[string() =~ /name2/] +'); } ); my $twig= new XML::Twig( PrettyPrint => 'indented', twig_handlers => + \%handlers); $twig->parse($xml); $twig->print; # output: <sites> <site siteid="ONE"> <name>name1</name> <address>address1</address> <contact>contact1</contact> </site> </sites>
L*
|
|---|