Add element in Xml with PowerShell

Need to add this element <ColourAddon>red</ColourAddon> inside GSIset in the following xml:

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

the code am using is this:

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

the result i get is this

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

and i want this:

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

any help?

Upvotes: 3

Views: 852

Answers (1)

G42
G42

Reputation: 10019

First create the element, then set the value.

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

Related: CreateElement documentation. Note how the two values refer to name and namespace, not name and "value" or "text" or similar.

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

Upvotes: 5

Related Questions