How to prevent XML::LibXML to save modified xml using self-closing tag

Viewed 812

The following working code reads my XML file containing lots of empty elements, then applies 2 changes and saves it again under different name. But it also changes empty elements like <element></element> to self-closing tags like <element /> which is unwanted.
How to save it not using self-closing tags? Or by another words how to tell XML::LibXML to use empty tags? The original file is produced in commercial application, which uses style with empty elements, so I want to sustain that.

#! /usr/bin/perl

use strict;
use warnings;
use XML::LibXML;

my $filename = 'out.xml';
my $dom = XML::LibXML->load_xml(location => $filename);
my $query = '//scalar[contains(@name, "partitionsNo")]/value';
for my $i ($dom->findnodes($query)) {
$i->removeChildNodes();
$i->appendText('16');
}

open my $out, '>', 'out2.xml';
binmode $out;
$dom->toFH($out);
# now out2.xml has only self-closing tags where previously 
# were used empty elements
2 Answers

There is a package variable

$XML::LibXML::setTagCompression

Setting it to a true value forces all empty tags to be printed as <e></e>, while a false value forces <e/>.

See SERIALIZATION in the Parser documentation.

Related