xml - 使用 PowerShell 在 Xml 中添加元素

标签 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>

我使用的代码是这样的:

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

有什么帮助吗?

最佳答案

先创建元素,再设置值。

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

关于xml - 使用 PowerShell 在 Xml 中添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53632419/

相关文章:

c# - 在 XDocument 中合并 XML 文件

python - 通过 'ElementTree' 在 Python 中使用命名空间解析 XML

javascript - 解析xml错误

powershell - 如何在 PowerShell 中查询 .pdb 文件?

java - Java 中的 XML 模板

xml - 模式\d{10} 是什么意思?

powershell - 如何从脚本中更改我正在运行的 powershell 版本?

powershell - 导出 Active Directory 中用户的所有属性和值

powershell - 如何在其他 Add-Type 类型定义中访问 Add-Type 定义的类型?

csv - 在 PowerShell 中将 Csv 的一行拆分为多行