xml中的正则表达式没有按预期工作 [英] Regex in xml not working as expected
问题描述
我是新手,我正在尝试搜索和替换 xml 文件中的字符串,如下所示:
I am novice here and I am trying to search and replace a string in a xml file which is as given below:
<name>xxx.yyy_zzz</name>
<constructor_arguments />
<parameters>
<parameter>
<name>Name</name>
<string>
<value>yyy</value>
</string>
</parameter>
<parameter>
<name>abc</name>
<bool>
<value>false</value>
</bool>
</parameter>
<parameter>
<name>abcd</name>
<bool>
<value>true</value>
</bool>
</parameter>
<parameter>
<name>aa</name>
<integer>
<value>10</value>
</integer>
</parameter>
<parameter>
<name>bb</name>
<integer>
<value>100</value>
</integer>
</parameter>
<parameter>
<name>runtime_disabled</name>
<bool>
<value>false</value>
</bool>
我尝试了以下将 runtime_disabled 值更改为 true 但它没有发生我期望发生的事情,谁能告诉为什么会这样并提供合适的解决方案使其正常工作
I have tried the following to change runtime_disabled value to true but it did not happen which I expect to happen, can anyone tell why is it so and provide suitable solution for the same to work
$data=~ s/(xxx\.i\yyy\_zzz\s*?<\/name>(.+?)runtime_disabled\s*?<\/name>\s*?<bool>\s*?<value>\s*?<value>.*?<\/value>)/$1true$2/g;
推荐答案
解析格式良好的 XML 实际上应该总是使用模块来完成.随着时间的推移,关于这一点已经说了很多,例如参见 此页面和这个页面 等等.我还听说真正糟糕的事情可能会过去 否则.
Parsing well-formed XML should practically always be done using modules. Much has been said about that over time, see for example this page and this page, among many others. I also hear that truly bad things may come to pass otherwise.
这里有一个例子,说明如何使用 XML::libXML.另一个优秀的模块是 XML::Twig.我完成了您的示例,使其成为格式良好的 XML 文件(如下代码所示).
Here is an example of how to do what you ask using XML::libXML. Another excellent module is XML::Twig. I completed your sample so to make it a well-formed XML file (shown below code).
use strict 'all';
use warnings;
use XML::LibXML;
my $file = 'file.xml';
my $doc = XML::LibXML->load_xml(location => $file, no_blanks => 1);
# Form the XPath expression used to find the 'name' nodes
my $xpath = '//doc/constructor_arguments/parameters/parameter/name';
foreach my $node ($doc->findnodes($xpath))
{
# Select the particular 'name' tag that is needed
if ($node->to_literal eq 'runtime_disabled')
{
# Query the parent node, for <name>'s sibling <bool>
foreach my $bval ($node->parentNode->findnodes('./bool/value/text()'))
{
my $content = $bval->toString;
$content =~ s/false/true/;
$bval->setData($content);
}
}
}
# Write a new file with the change
$doc->toFile('changed_' . $file, 1);
这是基本的,还有很多其他方法可以做到这一点.
This is meant to be basic, there are quite a few other ways to do the same.
发布的样本填充如下
<doc>
... posted text ...
</parameter>
</parameters>
</constructor_arguments>
</doc>
这篇关于xml中的正则表达式没有按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!