Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 232
Gregory Danenberg Avatar asked Jan 17 '23 13:01

Gregory Danenberg


2 Answers

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

like image 71
bvr Avatar answered Jan 20 '23 03:01

bvr


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.

like image 40
daxim Avatar answered Jan 20 '23 03:01

daxim