开发者

Generating formatted XML from a DOM using Perl

开发者 https://www.devze.com 2023-01-06 23:06 出处:网络
I wrote the following Perl script (below) in order t开发者_如何学运维o create simple XML file. The generated output is valid, but I have specific formatting requirements for the generated XML source c

I wrote the following Perl script (below) in order t开发者_如何学运维o 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>


See the documentation for toString

print $doc->toString(1);


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.


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> 


This is not an answer to your questions (you already have one). I just want to point out that

xmllint - command line XML tool (from libxml)

may help in several xml tasks like pretty-printing, encoding, verification. In this case:

perl yourscript | xmllint --format -
0

精彩评论

暂无评论...
验证码 换一张
取 消