用于在 XML 中查找和替换标记值的 Perl 代码 [英] Perl code for Find and replace a tag value in XML
本文介绍了用于在 XML 中查找和替换标记值的 Perl 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是我将使用的 XML:
Below is the XML I will be using:
我想编写一个 Perl 代码来搜索标签id"并将值ABC"替换为DEF".
I want to write a Perl code which search for tag 'id' and replace the value "ABC" with "DEF".
然而,上述 XML 的嵌套可以改变.所以我想制作一个通用代码,独立于其确切位置搜索标签id".
However the nesting of above XML can change. So I want to make a generalized code that search for the tag 'id' independently of its exact position.
到目前为止,我能够获得可以替换 ABC 中的值的逻辑,但这会使我的代码静态标记id"的位置.
Till now i am able to get the logic where i can replace the value in ABC but that makes my code static of the position of tag 'id'.
#!usr/bin/perl
use warnings;
use XML::Simple;
use Spreadsheet::ParseExcel;
use Data::Dumper;
my $FileName = 'sample.xls';
my $xml_file = 'hello.xml';
$par=$ARGV[0];
my $xml = XMLin($xml_file,
KeepRoot=>1,
ForceArray=>1,);
$xml->{a}->[0]->{id}='DEF';
XMLout(
$xml,
KeepRoot =>1 ,
NoAttr =>1,
OutputFile => $xml_file,
);
}
推荐答案
XPath 能够找到节点,而无需知道在树中的位置.
XPath is able to find nodes without needing to know the position in the tree.
use strictures;
use XML::LibXML qw();
my $dom = XML::LibXML->load_xml(string => <<'XML');
<a>
<id>ABC</id>
<class />
<gender />
</a>
XML
for my $id ($dom->findnodes('//id[string()="ABC"]')) {
$id->removeChildNodes;
$id->appendText('DEF');
}
print $dom->toString
这篇关于用于在 XML 中查找和替换标记值的 Perl 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文