【问题标题】:Powershell XML replace element with new valuePowershell XML 用新值替换元素
【发布时间】: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 }}'

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

【问题讨论】:

    标签: xml powershell


    【解决方案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 }}' } '''
      • 我最终使用了这个版本,但两个答案都是正确的
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多