Powershell XML 用新值替换元素

Posted

技术标签:

【中文标题】Powershell XML 用新值替换元素【英文标题】:Powershell XML replace element with new value 【发布时间】:2022-01-11 09:47:52 【问题描述】:

我有一个包含许多属性的 xml 文件

 <configuration>
  <property>
    <name>access.key</name>
    <value>fred</value>
  </property>
  <property>
    <name>access.secret</name>
    <value>blog</value>
  </property>
</configuration>

我想根据属性名称替换属性值。我尝试了很多方法。我遇到了问题,因为名称和值是属性的元素而不是属性。我虽然这会起作用,但没有运气。

    $file = "site.xml"
    $xml = New-Object XML
    $xml.Load($file)
    $nodes = $xml.SelectNodes('/configuration/property') 
    foreach ($node in $nodes) 
      $property = $node.Attributes.GetNamedItem("name").Value
      if ($property -eq 'access.key')
        
          $node.Attributes.SetNamedItem("value").Value = ' access_key '
        
    

    $xml.Save($file)

以下内容发生了变化,但它改变了 name 的值,这是有道理的,因为我选择了 SingleNode 属性名称。如何根据名称更改属性值?

     $node =  $xml.SelectSingleNode("/configuration/property/name[.= 'access.key']")
     $node.innerText = ' access_key '

这似乎很简单,可能是,希望有人能解释一下。

【问题讨论】:

【参考方案1】:

我使用您包含的 .xml 的内容进行了测试,我认为下面的脚本会满足您的需求。

我删除了$property 变量,只是更改了If 语句以要求$node.name 等于您要查找的名称。如果是,那么它将在完成ForEach 循环后更新$node.value 并保存.xml:

$file = "site.xml"
$xml = New-Object XML
$xml.Load($file)
$nodes = $xml.SelectNodes('/configuration/property') 
foreach ($node in $nodes) 
  if ($node.name -eq 'access.key')
    
        $node.Value = ' access_key '
    


$xml.Save($file)

【讨论】:

【参考方案2】:

有多种方法可以做到这一点:

$fileName = 'D:\Test\site.xml'

$xml = New-Object -TypeName 'System.Xml.XmlDocument'
$xml.Load($fileName)

$xml.DocumentElement.ChildNodes | Where-Object  $_.name -eq 'access.key'  | ForEach-Object  $_.name = 'access_key' 
# or
# $xml.configuration.property | Where-Object  $_.name -eq 'access.key'  | ForEach-Object  $_.name = 'access_key' 
# or
# $xml.SelectNodes("//property/name[text() = 'access.key']") | ForEach-Object  $_.innerText = 'access_key' 

$xml.Save($fileName)

【讨论】:

我只测试了第一个,但是有这些变化:''' $xml.DocumentElement.ChildNodes | Where-Object $_.name -eq 'access.key' | ForEach-Object $_.value = ' access_key ' ''' 我最终使用了这个版本,但两个答案都是正确的

以上是关于Powershell XML 用新值替换元素的主要内容,如果未能解决你的问题,请参考以下文章

表单元素不返回新值

使用以下逻辑编写 Powershell 脚本的指南 [关闭]

用新值更新不可变的 js 嵌套对象

powershell Xml替换节点文本

用新的替换 d3.js 路径转换?

Powershell 中非常大的 XML 文件