Powershell根据其他键值更新xml键值 [英] Powershell update xml key value based on other key value

查看:35
本文介绍了Powershell根据其他键值更新xml键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一些 powershell,它将根据同一节点中另一个键值对的值更新 xml 键值对的值.示例 xml:

I'm trying to write some powershell that will update the value of a xml key value pair based on the value of another key value pair in the same node. Example xml:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <plugins>
  <plugin pluginType="plugin1" polling_internal="2" polling_unit="M" enabled="true">
      <params>
        <add key="Server" value="server1.local" />
        <add key="database" value="databasename1" />
      </params>
    </plugin>
  <plugin pluginType="plugin2" polling_internal="2" polling_unit="M" enabled="true">
      <params>
        <add key="Server" value="server2.local" />
        <add key="database" value="databasename2" />
      </params>
    </plugin>
 </plugins>
</configuration>

真实文件中有数百个插件.我想找到所有名为 databasename1 的数据库实例 - <add key="database" value="databasename1" 并使用服务器名称 server2.local 例如更新相应的服务器密钥.

The real file has hundreds of plugins in it. I want to find all instances of databases called databasename1 - <add key="database" value="databasename1" and update the corresponding Server key with server name server2.local for example.

我知道这可以通过 select-xml 和 xpath 来完成,但它超出了我的范围.非常感谢任何帮助.

I know this can be done with select-xml and xpath, but its beyond me. Any assistance much appreciated.

推荐答案

您可以使用此 XPath 根据您解释的条件获取所有 value 属性(xpath 格式化以提高可读性):

You can use this XPath to get all value attribute according to the criteria you explained (xpath formatted for readability) :

//plugin
    /params[add[@key='database' and @value='databasename1']]
        /add[@key='Server']
            /@value

最复杂的部分(上面 xpath 中的第 2 行)意味着搜索 节点,条件为:具有子节点 具有属性 key 值等于database",属性 value 值等于databasename1".其余部分与其他答案中演示的内容类似:

The most complicated part (line 2 in above xpath) means search <params> node with criteria : has child node <add> having attribute key value equals "database" and attribute value value equals "databasename1". The rest is similar to what demonstrated in the other answer :

[XML]$xml = #load XML file
$xpath = "/configuration/plugins/plugin/params[add[@value='databasename1' and @key ='database']]/add[@key='Server']/@value"
$nodes = $xml.SelectNodes($xpath)

foreach ($n in $nodes) {
    $n.value = "server2.local"
}
#save XML back to file

这篇关于Powershell根据其他键值更新xml键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆