使用PowerShell在Xml中添加元素

时间:2018-12-05 12:31:54

标签: xml powershell

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

<?xml version="1.0" standalone="yes"?>
<GSIExplorer>
  <GSISet>
    <ID>local</ID>
    <GSIServer>localhost</GSIServer>
    <ALERT_TIMEOUT>30</ALERT_TIMEOUT>
  </GSISet>
</GSIExplorer>

正在使用的代码是这样的:

 [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")

我得到的结果就是这个

<?xml version="1.0" standalone="yes"?>
<GSIExplorer>
  <GSISet>
    <ID>local</ID>
    <GSIServer>localhost</GSIServer>
    <ALERT_TIMEOUT>30</ALERT_TIMEOUT>
    <Colouraddon xmlns="asda" />
  </GSISet>
</GSIExplorer>

,我想要这个:

<?xml version="1.0" standalone="yes"?>
    <GSIExplorer>
      <GSISet>
        <ID>local</ID>
        <GSIServer>localhost</GSIServer>
        <ALERT_TIMEOUT>30</ALERT_TIMEOUT>
        <ColourAddon>red</ColourAddon>
      </GSISet>
    </GSIExplorer>

有帮助吗?

1 个答案:

答案 0 :(得分:2)

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

[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")

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

# [1] original answer
$Xmlnew.GSIExplorer.GSISet.AppendChild($test)
$Xmlnew.GSIExplorer.GSISet.ColourAddon = "red"