The code below uses XML::Twig to edit an XML file. If parsefile is used the unedited part of the output is double spaced. If parse is used the output is as desired. What's going on here? How do I fix it? (I know it shouldn't matter for interpretation of the created XML.)
Update: The "double spacing" is due to extra CR characters.
use warnings; use strict; use XML::Twig; # Generate the XML file my $str = do {local $/; <DATA>}; open OUT, '>', 'temp.xml'; print OUT $str; close OUT; # Troublesome code print "******* Troublesome version\n"; my @fileList = qw(first second third); my $sub = bindArgs (\&insertFiles, \@fileList); my $twig = XML::Twig->new ( discard_spaces => 1, pretty_print => 'indented', twig_roots => {'sourceFiles' => $sub,}, # Insert file list twig_print_outside_roots => 1, # Print the rest ); $twig->parsefile ('temp.xml'); # Ok code print "******* Ok version\n"; $twig = XML::Twig->new ( discard_spaces => 1, pretty_print => 'indented', twig_roots => {'sourceFiles' => $sub,}, # Insert file list twig_print_outside_roots => 1, # Print the rest ); $twig->parse ($str); sub bindArgs { my ($sub, @args) = @_; return sub {$sub->(@args, @_);}; } sub insertFiles { my ($sourceFiles, $twig, $node) = @_; for (@$sourceFiles) { my $eFile = $twig->root->new (sourcefile => $_); # create the +element $eFile->paste (first_child => $node); } $node->print (); } __DATA__ <?xml version="1.0" encoding="utf-8"?> <experiment title="Blood Pressure" version="1.2" softwareVersion="1.1" +> <sourceFiles> </sourceFiles> <dataFiles> <dataFile>arm_pulse.dat</dataFile> <dataFile>bp_Ex1.dat</dataFile> <dataFile>bp_pulse.dat</dataFile> <dataFile>cuff practice.dat</dataFile> </dataFiles> </experiment>
Prints:
******* Troublesome version <?xml version="1.0" encoding="utf-8"?> <experiment title="Blood Pressure" version="1.2" softwareVersion="1.1" +> <sourceFiles> <sourcefile>third</sourcefile> <sourcefile>second</sourcefile> <sourcefile>first</sourcefile> </sourceFiles> <dataFiles> <dataFile>arm_pulse.dat</dataFile> <dataFile>bp_Ex1.dat</dataFile> <dataFile>bp_pulse.dat</dataFile> <dataFile>cuff practice.dat</dataFile> </dataFiles> </experiment> ******* Ok version <?xml version="1.0" encoding="utf-8"?> <experiment title="Blood Pressure" version="1.2" softwareVersion="1.1" +> <sourceFiles> <sourcefile>third</sourcefile> <sourcefile>second</sourcefile> <sourcefile>first</sourcefile> </sourceFiles> <dataFiles> <dataFile>arm_pulse.dat</dataFile> <dataFile>bp_Ex1.dat</dataFile> <dataFile>bp_pulse.dat</dataFile> <dataFile>cuff practice.dat</dataFile> </dataFiles> </experiment>
Update: Fixed unrelated bug in code
In reply to Anomalous double spaced output from XML::Twig by GrandFather
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |