http://www.perlmonks.org?node_id=922595


in reply to Search and replace query

Two approaches using XML::Twig, too bad the xpath support is dated
#!/usr/bin/perl -- use XML::Twig; BEGIN { *XML::Twig::Elt::x = *XML::Twig::Elt::get_xpath; } use strict; use warnings; my $str = <<'EOF'; <fudge> <factory> <drop> <bindname>qqqqq</bindname> <bindpass>welcome</bindpass> </drop> <drop> <bindname>abcde</bindname> <bindpass>welcome</bindpass> </drop> </factory> </fudge> EOF { my $t = XML::Twig->new( pretty_print => 'indented', twig_handlers => { '//factory/drop' => sub { if ( not $_->x('bindname[string()=~/abcde/]') ) { if ( my ($pass) = $_->x('bindpass[string()="welcom +e"]') ) { $pass->set_text( uc $pass->text ); } } }, }, ); $t->parse($str); $t->print(); } { my $bozo = 0; my $t = XML::Twig->new( pretty_print => 'indented', twig_handlers => { '//factory/drop/bindname' => sub { $bozo = 1 if $_->text =~ /abcde/; }, '//factory/drop/bindpass' => sub { if ( not $bozo and $_->text =~ /welcome/ ) { $_->set_text( uc $_->text ); } $bozo = 0; }, }, ); $t->parse($str); $t->print(); } __END__
And a similar one using XML::XSH2, too bad it doesn't have diagnostics/splain
#!/usr/bin/perl -- use strict; use warnings; use XML::XSH2; xsh(<<'__XSH__'); open "fudge.xml"; ls --indent /; pwd ; cd /fudge/factory ; pwd ; foreach //drop { if not( bindname/text()[contains(.,'abcde')] ){ set bindpass xsh:subst( bindpass/text(), "welcome", "W-e-l-c-o-m-e", "i" ); }; }; ls --indent /; save --indent :b /; # overwrite original file, :b means backup __XSH__ __END__ $ perl xsh.922557.pl parsing fudge.xml done. <?xml version="1.0"?> <fudge> <factory> <drop> <bindname>qqqqq</bindname> <bindpass>welcome</bindpass> </drop> <drop> <bindname>abcde</bindname> <bindpass>welcome</bindpass> </drop> </factory> </fudge> Found 1 node(s). / /fudge/factory <?xml version="1.0"?> <fudge> <factory> <drop> <bindname>qqqqq</bindname> <bindpass>W-e-l-c-o-m-e</bindpass> </drop> <drop> <bindname>abcde</bindname> <bindpass>welcome</bindpass> </drop> </factory> </fudge> Found 1 node(s). Document saved into file 'fudge.xml'. $ ls -loanh fudge* -rw-rw-rw- 1 0 252 2011-08-26 06:05 fudge.xml -rw-rw-rw- 1 0 234 2011-08-26 06:05 fudge.xml~