tags:

views:

37

answers:

3

I wrote the following Perl script (below) in order to create simple XML file. The generated output is valid, but I have specific formatting requirements for the generated XML source code.

How can I change my script to add the whitespace I desire?

#!/usr/bin/perl

use warnings;
use XML::LibXML;


my $doc  = XML::LibXML::Document->new; 
my $root = $doc->createElement('LEVEL1');
$doc->setDocumentElement($root);

my $system = $doc->createElement('LEVEL2');
$root->appendChild($system);

my $install = $doc->createElement('LEVEL3');
$system->appendChild($install);

print $doc->toString;

Output of the script:

<?xml version="1.0"?>
<LEVEL1><LEVEL2><LEVEL3/></LEVEL2></LEVEL1>

Desired output:

  <?xml version="1.0"?>
  <LEVEL1>
     <LEVEL2>
      <LEVEL3/> 
     </LEVEL2>
   </LEVEL1>
A: 

Your output as you listed it in example 1 is correct. Tabs and spaces mean nothing to XML; they are only there for humans to make it easier to see the structure. But if you still want to do is make sure the output has that structure, one way is to create the new doc out of a string (in the right format) instead of from nothing.

MJB
my target is to change the script in order to make XML as example 2I understand that example 1 is correct but how I can manipulate the XML as example 2 ?Yael
yael
@yael: Sorry -- the question as initially written sounded like you thought the XML was invalid.
MJB
+4  A: 

See the documentation for toString

print $doc->toString(1);
David Dorward
A: 

hi all I find the solution, I add the following lines

 my @lines = split /\n/, $doc->toString(1);
  shift @lines;


  foreach (@lines) {
  print "$_\n";
  }

and now I get

  <LEVEL1> 
    <LEVEL2> 
     <LEVEL3/> 
    </LEVEL2> 
  </LEVEL1> 
yael