This was going to be a SOPW but became a meditation because in the process of cleaning the code up to the point where I could post it as a SOPW I resolved the problem. However it seemed sufficiently non-intuitive to me (I didn't get it right first time) and seems not to be covered by any previous SOPW or Meditation that it seemed worth while to post anyway.
I wanted to filter an XML file in place. My first attempts tried to use twig_handlers to do the editing and I simply could not get it to work. Re-reading the documentation while playing around with my sample code first led me to using twig_roots handlers instead and finally to the discovery that I needed $elt->print (); in the handler. There were a few more (unimportant) steps along the way, but the final working example code is:
use strict; use warnings; use XML::Twig; open my $XML, '>', 'temp.xml'; print $XML <<XML; <root> <elt attr="wibble" /> </root> XML close $XML; my $twig = XML::Twig->new ( twig_roots => {elt => \&FixName}, twig_print_outside_roots => 1 ); $twig->parsefile_inplace ('temp.xml', '.bak'); $twig = 0; @ARGV = 'temp.xml'; print "::$_" while <>; sub FixName { my ($t, $elt) = @_; $elt->set_att ('attr', 'updated'); $elt->print (); }
Prints:
::<root> :: <elt attr="updated"/> ::</root>
The :: prefixes on the lines are to distinguish between lines from the file and stuff that XML::Twig prints to STDOUT by default when flush is called (and possibly at other times). Initially it wasn't clear where and why stuff was being printed rather than written to the file.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: XML::Twig parse_inplace - it actually works
by Jenda (Abbot) on May 16, 2008 at 12:26 UTC |