perl-从xml文件中删除节点 [英] perl - remove node from xml file
问题描述
我有一个XML文件,我想读取它-删除节点-保存它. 我从终端(perl script.pl)运行perl
I have a XML file, and I want to read it - remove a node - save it. I run perl from terminal (perl script.pl)
示例XML(filename.xml):
example XML (filename.xml):
<?xml version="1.0" encoding="UTF-8"?>
<twice>
<inner>
<twice>
<name>John</name>
<surname>Smith</surname>
</twice>
<twice>
<name>Alan</name>
<surname>Bowler</surname>
</twice>
<twice>
<name>Michael</name>
<surname>Deck</surname>
</twice>
</inner>
</twice>
perl脚本示例(script.pl):
example perl script (script.pl):
use strict;
use warnings;
use XML::LibXML;
my $filename = "filename.xml";
my $parser = XML::LibXML->new();
my $xmldoc = $parser->parse_file($filename);
for my $dead ($xmldoc->findnodes(q{/twice/inner/twice[surname = "Bowler"]})) {
$dead->unbindNode;
}
print $xmldoc->toString;
现在,它将在终端中输出预期结果,但不保存文件.
预期结果(filename.xml):
Now it outputs the expected result in terminal, but without saving the file.
Expected result (filename.xml):
<?xml version="1.0" encoding="UTF-8"?>
<twice>
<inner>
<twice>
<name>John</name>
<surname>Smith</surname>
</twice>
<twice>
<name>Michael</name>
<surname>Deck</surname>
</twice>
</inner>
</twice>
我已经搜索了多个小时,却找不到任何内容,如果重复的话,抱歉!
这是我第一次使用perl,因此,欢迎您的任何帮助,谢谢.
I have searched for many hours and couldn't find anything, sorry if it's a duplicate!
This is my first experience with perl so please any help would be welcomed, thanks.
推荐答案
使用toString时,文档说要这样做:
When using toString the docs say to do it like this:
open my $out_fh, '>', 'somefile.xml';
print {$out_fh} $xmldoc->toString;
您还可以使用toFile()
函数将其保存:
You can also use the toFile()
function to save it:
$xmldoc->toFile("someFile.xml");
也可以引用文档(这是我所做的一切),您可以将format参数传递给这些函数.
Also to quote the docs, (which is all I did) you can pass the format parameter to these functions.
如果$ format为0,则该文档将按原先的方式转储 解析
If $format is 0, than the document is dumped as it was originally parsed
如果$ format为1,libxml2将添加可忽略的空格,因此节点 内容更易于阅读.现有的文本节点将不会更改
If $format is 1, libxml2 will add ignorable white spaces, so the nodes content is easier to read. Existing text nodes will not be altered
如果$ format为2(或更高),libxml2将充当$ format == 1,但它会 在每个文本节点上添加一个前导和尾随的换行符.
If $format is 2 (or higher), libxml2 will act as $format == 1 but it add a leading and a trailing line break to each text node.
给你
$xmldoc->toFile("someFile.xml", $format);
或
print {$out_fh} $xmldoc->toString($format);
这篇关于perl-从xml文件中删除节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!