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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |