【问题标题】:Powershell: How to update specific character of attribute value of XML nodePowershell:如何更新XML节点属性值的特定字符
【发布时间】:2022-01-08 18:59:49
【问题描述】:

我是探索 XML 到 Powershell 的新手。 我这里有一个示例 XML,我需要编辑它的值。

示例 XML

<Configuration>
   <System>
      <Address link = "http://www.thispage.com" page = "first" />
      <Address link = "http://www.thispage.com" page = "second"/>
  </System>
</Configuration>

这是我编辑 XML 时的“应该是结果”。

<Configuration>
   <System>
      <Address link = "https://www.thispage.com" page = "first" />
      <Address link = "https://www.thispage.com" page = "second"/>
  </System>
</Configuration>

我试过这段代码:

$fileName = "C:\Project\XML-file\SampleXML.config"
$xmlContent = [xml](Get-Content $fileName)

$xmlContent | Select-Xml -XPath 'Configuration/system/Address' | ForEach-Object {$_.node.link -replace 'http','https'}
$xmlContent.save($fileName)

在这段代码中,值没有被替换,但是文件正在被保存(文件没有变化)。但我可以在 Powershell 控制台中看到 http 被替换为 https

我也试过 SetAttribute 命令,但它正在替换链接的整个值。 例如:

<Configuration>
   <System>
      <Address link = "https" page = "first" />
      <Address link = "https" page = "second"/>
  </System>
</Configuration>

感谢您的投入!

【问题讨论】:

    标签: xml powershell


    【解决方案1】:

    您的 xml 未使用 &lt;/Configuration&gt; 正确关闭。

    要加载一个xml,最好使用下面的方法然后使用$xmlContent = [xml](Get-Content $fileName),因为.Load()方法可以确保你得到正确的文件编码。

    试试

    $fileName = "C:\Project\XML-file\SampleXML.config"
    $xmlContent = New-Object -TypeName 'System.Xml.XmlDocument'
    $xmlContent.Load($fileName)
    
    $xmlContent.DocumentElement.System.ChildNodes | ForEach-Object { $_.link = $_.link -replace '^http:', 'https:' }
    # or
    # $xmlContent.Configuration.System.Address | ForEach-Object { $_.link = $_.link -replace '^http:', 'https:' }
    # or
    # $xmlContent.SelectNodes('//Address') | ForEach-Object { $_.SetAttribute('link', ($_.GetAttribute('link') -replace '^http:', 'https:')) }
    
    $xmlContent.Save($fileName)
    

    【讨论】:

    • 我已经用正确的 编辑了 xml 的关闭。感谢您的意见,我已经尝试过您的建议,它对我有用。
    • @Mariyah 感谢您告诉我。如果您发现我的回答解决了您的问题,请单击左侧的大复选标记图标将其标记为“已完成”。这将帮助其他有类似问题的人更轻松地找到它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多