XML::LibXML写入XML时如何删除标题

4
当我使用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->toStringC14N(1)进行操作,但这并没有帮助...
3个回答

5

daxim和rpg的回答都可以实现这个功能,但是需要强调的是,使用$tree->toString()而不是$root->toString()来获取整个文件。


3

请查看XML::LibXML::Document 中的toFile。务必阅读您正在使用的软件文档。

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错误检查。

10x。CPAN 表示它与 toString 相同,但在处理大文件时更好,因此我没有尝试过。 - Gregory Danenberg

1
请尝试这个。
$tree->toFile ($file);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接