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.


Perl is environmentally friendly - it saves trees

In reply to XML::Twig parse_inplace - it actually works by GrandFather

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.