benizi has asked for the wisdom of the Perl Monks concerning the following question:
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>
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: XML::Twig outputting root element start tag twice
by Tanktalus (Canon) on Apr 18, 2006 at 18:34 UTC | |
by benizi (Hermit) on Apr 18, 2006 at 19:06 UTC | |
by mirod (Canon) on Apr 19, 2006 at 06:06 UTC | |
by benizi (Hermit) on Apr 25, 2006 at 15:20 UTC |