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...
Both daxim and rpg answers do that, but to emphasize - use $tree->toString()
instead of $root->toString()
to get whole file.
See toFile
in XML::LibXML::Document. Do read the documentation of the software you're working with.
use strictures;
use XML::LibXML qw();
my $file = 'fnord.xml';
my $name = 'test.name';
my $new_val = 'foo';
my $parser = XML::LibXML->new;
my $tree = $parser->parse_file($file);
my $root = $tree->getDocumentElement;
my $searchPath = "/configuration/property[name='$name']/value/text()";
my ($val) = $root->findnodes($searchPath);
$val->setData($new_val);
$tree->toFile($file);
The file routines automatically raise exceptions, no need for the traditional Perl error checking.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With