Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Search and replace query

by Anonymous Monk
on Aug 26, 2011 at 13:08 UTC ( #922595=note: print w/replies, xml ) Need Help??


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~

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://922595]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2019-03-21 03:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How do you Carpe diem?





    Results (106 votes). Check out past polls.

    Notices?
    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!