替换特定标记的 XML 文件中的值 [英] Replacing a value in a XML file for a particular tag
问题描述
我的 Linux 机器上有一个 XML 文件 MyFile.xml.
I have a XML file, MyFile.xml on my Linux machine.
<?xml version="1.0" encoding="UTF-8"?>
<project>
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<env name="envvar" value="/opt/environment/environment.properties" />
<env name="JDBC_Driver" value="/opt/JDBC/ojdb6.jar" />
<env name="agent/enable" value="true" />
</project>
我需要将 env 名称的值更改为
标记在 XML 文件中,每当我收到要求时."false"
(当它为真时)和 "true"
(当它为假时)="agent/enable"
I need to change the value to "false"
(when it is true) and "true"
(when it is false) for the env name="agent/enable"
tag in the XML file whenever I get a requirement.
我只是想为此使用一些 shell 脚本.我知道这可以在 Linux 中使用 Sed 命令来完成,但我不擅长正则表达式.这样每当我需要更改时,我都可以运行脚本.
I just wanted to use some shell script for this. I know this can be done using Sed command in Linux, but I'm not good at regular expressions. So that whenever I get a requirement to change I can just run a script.
注意:脚本应更改 XML 文件,并应保存在具有相同名称的文件系统中.
Note: script should change the XML file and should be saved on the file system with same name.
推荐答案
不要尝试使用纯文本工具编辑 XML;它只能以糟糕的方式结束.当他们在 XML 中插入换行符或将 <foo/>
节点更改为 <foo></foo>
时,没有人希望他们的 XML 工具中断,但是如果它们基于 sed(并且不是非常复杂),它们就会这样做.
Do not attempt to edit XML with plain-text tools; it can only end badly. Nobody expects their XML tools to break when they insert a newline into the XML or change a <foo/>
node to <foo></foo>
, but they will if they're based on sed (and not ridiculously complex).
相反,使用适当的 XML 解析工具,例如 xmlstarlet
:
Instead, use a proper XML-parsing tool such as xmlstarlet
:
xmlstarlet ed --inplace -u '/project/env[@name="agent/enable"]/@value' -x 'string(not(. = "true"))' filename.xml
说明
xmlstarlet ed --inplace -u <foo> -x <bar> filename.xml
更新适合 XPath 表达式的节点
以具有 XPath 表达式的值
,
updates nodes that fit the XPath expression <foo>
to have the value of the XPath expression <bar>
,
/project/env[@name="agent/enable"]/@value
是一个 XPath 表达式,它选择 env
节点的 value
属性,其 name
属性为 agent/enable
并且它是 project
根节点的子节点 -- 这应该描述您想要适当更改的值 -- 和
is an XPath expression that selects the value
attribute of env
nodes whose name
attribute is agent/enable
and that are a child of the project
root node -- this should describe the value you want to change adequately -- and
string(not(. = "true"))
是一个 XPath 表达式,如果当前检查的值为 "true"
则为 false
,否则为 true
.当前检查的值是正在更新的 value
属性的旧值.
is an XPath expression that is false
if the currently inspected value is "true"
and true
otherwise. The currently inspected value is the old value of the value
attribute that's being updated.
这篇关于替换特定标记的 XML 文件中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!