I'm sure I'm missing some interaction between the various options, but I was wondering if someone (mirod?) could tell me how to accomplish the following. I have an XML document that I want to process with XML::Twig. I want the output document to retain the formatting characteristics of the input document. I also want to use twig_roots, since the file will not fit into memory, and is record-based. (i.e. the processing of each record is self-contained.). I used twig_print_outside_roots, because I want to specify a filehandle for the default prints/flushes. (Is there something more appropriate for that purpose?) The problem is that the root (wrapper) element's start tag is being output twice.

Example input:

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE foo SYSTEM "/path"> <foo version="blah"> <record>stuff</record> <record>stuff 2</record> </foo>

Desired output:

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE foo SYSTEM "/path"> <foo version="blah"> <record>altered stuff</record> <record>altered stuff 2</record> </foo>

My attempt:

#!/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 } }, empty_tags => 'html', keep_encoding => 1, keep_spaces => 1, ); $p->parsefile("in.xml"); print "DONE\n";

Actual output:

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE foo SYSTEM "/path"> <foo version="blah"> <foo version="blah"><record>altered stuff</record> # the extra <foo ve +rsion="blah"> is the problem. <record>altered stuff 2</record> </foo>

In reply to 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.