使用 PowerShell 在 Xml 中添加元素

Mar*_*los 3 xml powershell

需要<ColourAddon>red</ColourAddon>在以下 xml 中的 GSIset 中添加此元素:

<?xml version="1.0" standalone="yes"?>
<GSIExplorer>
  <GSISet>
    <ID>local</ID>
    <GSIServer>localhost</GSIServer>
    <ALERT_TIMEOUT>30</ALERT_TIMEOUT>
  </GSISet>
</GSIExplorer>
Run Code Online (Sandbox Code Playgroud)

我使用的代码是这样的:

 [xml]$Xmlnew = Get-Content "C:\Program Files (x86)\GSI\gsiSettings\gsiPSSSettings2.xml"
        $test = $Xmlnew.CreateElement("ColourAddon","red")
        $Xmlnew.GSIExplorer.GSISet.AppendChild($test)
        $Xmlnew.save("C:\Program Files (x86)\GSI\gsiSettings\gsiPSSSettings3.xml")
Run Code Online (Sandbox Code Playgroud)

我得到的结果是这样的

<?xml version="1.0" standalone="yes"?>
<GSIExplorer>
  <GSISet>
    <ID>local</ID>
    <GSIServer>localhost</GSIServer>
    <ALERT_TIMEOUT>30</ALERT_TIMEOUT>
    <Colouraddon xmlns="asda" />
  </GSISet>
</GSIExplorer>
Run Code Online (Sandbox Code Playgroud)

我想要这个:

<?xml version="1.0" standalone="yes"?>
    <GSIExplorer>
      <GSISet>
        <ID>local</ID>
        <GSIServer>localhost</GSIServer>
        <ALERT_TIMEOUT>30</ALERT_TIMEOUT>
        <ColourAddon>red</ColourAddon>
      </GSISet>
    </GSIExplorer>
Run Code Online (Sandbox Code Playgroud)

有什么帮助吗?

gms*_*man 5

首先创建元素,然后设置值。

[xml]$Xmlnew = Get-Content "C:\Program Files (x86)\GSI\gsiSettings\gsiPSSSettings2.xml"
$test = $Xmlnew.CreateElement("ColourAddon")

# thanks to Jeroen Mostert's helpful comment. original at bottom of post [1]
$Xmlnew.GSIExplorer.GSISet.AppendChild($test).InnerText = "red" 

$Xmlnew.save("C:\Program Files (x86)\GSI\gsiSettings\gsiPSSSettings3.xml")
Run Code Online (Sandbox Code Playgroud)

相关: CreateElement文档。请注意这两个值如何引用名称和命名空间,而不是名称和“值”或“文本”或类似内容。

# [1] original answer
$Xmlnew.GSIExplorer.GSISet.AppendChild($test)
$Xmlnew.GSIExplorer.GSISet.ColourAddon = "red"
Run Code Online (Sandbox Code Playgroud)