First, you're missing the end-flush. Before you're really "DONE", you need to add $p->flush(). That gets the extra </foo> tag you're missing in your output. Not that you want it, but once you fix the other problem, you'll want it back.

Second, it's the twig_print_outside_roots flag that's doing it. Remove that. Instead, change your flush calls (including the new one) to have the param "$outfh". Now you'll flush to that file.

That leaves me with:

#!/usr/bin/perl use strict; use warnings; use XML::Twig; open my $outfh, '>', "out.xml" or die ">out.xml:$!"; my $p = XML::Twig->new( #twig_print_outside_roots => $outfh, twig_roots => { record => sub { $_->set_text("altered ".$_->text); shift->flush($outfh), } }, empty_tags => 'html', keep_encoding => 1, keep_spaces => 1, ); $p->parsefile("in.xml"); $p->flush($outfh); print "DONE\n";
As to why, ... I'm not sure.

Hope that helps,

Update: Ok, I see you really want the twig_print_outside_roots feature. It doesn't seem to do what you want it to, though. I am curious, though, as to why the formatting matters - this is XML, after all...


In reply to Re: XML::Twig outputting root element start tag twice by Tanktalus
in thread XML::Twig outputting root element start tag twice by benizi

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.