需要添加这个元素<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/