Question

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...

Était-ce utile?

La solution

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

Autres conseils

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.

Please try this

$tree->toFile ($file);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top