写入xml时,XML :: LibXML删除标题

时间:2012-02-09 07:02:47

标签: xml perl xml-libxml

当我使用XML :: LibXML更新值时,前两行被删除。 我希望保留xml,除了一个更新的值。

我原来的xml是:

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

...

代码是:

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);

我尝试使用print UPDXML $ root-&gt; toStringC14N(1),但它没有帮助......

3 个答案:

答案 0 :(得分:5)

daxim和rpg的答案都是这样做的,但要强调的是 - 使用$tree->toString()代替$root->toString()来获取整个文件。

答案 1 :(得分:3)

toFile in XML::LibXML::Document。请阅读您正在使用的软件的文档。

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);

文件例程自动引发异常,不需要传统的Perl错误检查。

答案 2 :(得分:1)

请试试这个

$tree->toFile ($file);