Question

For some reason when I append element to xml file, it's written in one line, i.e. not formatted

Original xml:

<configuration>
 <property>
 <name>test1</name>
</property>
</configuration>

my $parser =XML::LibXML->new();
my $doc    =$parser->parse_file($file) or die $!;
my $root   =$doc->getDocumentElement;
my $searchPath="/configuration";
my ($val)=$root->findnodes($searchPath);
my $propTag=$doc->createElement("property");
$val->appendChild($propTag);
my $nameTag=$doc->createElement("name");
$nameTag->appendTextNode($name);
$propTag->appendChild($nameTag);
$doc->setDocumentElement($root);
$doc->toFile($file,1);

Which resulted with:

<configuration>
 <property>
    <name>test1</name>
 </property>
  <property><name>test2</name></property></configuration>

Instead of:

<configuration>
 <property>
    <name>test1</name>
 </property>
 <property>
   <name>test2</name>
  </property>
 </configuration>
Was it helpful?

Solution

You can run xmllint --format on the output of your Perl script.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top