Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add element in Xml with PowerShell

Tags:

powershell

xml

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?

like image 383
Marios Anagnostopoulos Avatar asked Dec 28 '25 19:12

Marios Anagnostopoulos


1 Answers

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"
like image 53
G42 Avatar answered Dec 31 '25 13:12

G42