Search code examples
xmlperlxml-libxml

XML::LibXML remove heading when write to xml


When I update value with XML::LibXML the first two lines are removed. I want to preserve the xml as is, except one updated value.

My original xml is:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
 <property>
   <name>test.name</name>
   <value>help</value>
   <description>xml issue</description>
 </property>

....

And the code is:

my $parser =XML::LibXML->new();
my $tree   =$parser->parse_file($file) or die $!;
my $root   =$tree->getDocumentElement;

my $searchPath="/configuration/property[name=\"$name\"]/value/text()";
my ($val)=$root->findnodes($searchPath);

$val->setData($new_val);
open (UPDXML, "> $file") or die "ERROR: Failed to write into $file...";
 print UPDXML $root->toString(1);
close (UPDXML);

I tried with print UPDXML $root->toStringC14N(1) but it does not help...


Solution

  • Both daxim and rpg answers do that, but to emphasize - use $tree->toString() instead of $root->toString() to get whole file.