Problem adding element to XML file

Hi all,

I am new to Powershell so please be gentle. I am trying to add a new element to several sections of an XML document.

$xml = [xml](Get-Content "test.xml")

$root = $xml.DocumentElement
$child = $xml.CreateElement("ENV")
$child.SetAttribute("Id","NewID")
$child.InnerXML = "New Text"
$nodes = $xml.SelectNodes("//ENV[@Id='E3']")
foreach ($node in $nodes) {
    $parent = $node.ParentNode
    $parent.InsertAfter($child,$parent.FirstChild)
    $parent.outerXML
}
$xml.save("test2.xml")

test.xml

When I run this the visual output looks correct, with 4 new elements shown, but the saved XML file only has 1 new element in it (the last occurence). I am totally confused and hope that someone can tell me what I have done wrong!

TIA.

BUMP. Is anyone able to tell me what I am doing wrong here? Thanks.

on top of my head : Try putting the save inside the loop.

This is not unique to PowerShell. This would have happened to you doing it this way in any language.

It’s because you have your needed elements outside of the loop , and thus have one. To repeat it per node, you need to tell the language to do so.

$xml = [xml](Get-Content '.\test.xml')

$root = $xml.DocumentElement
$nodes = $xml.SelectNodes("//ENV[@Id='E3']")

foreach ($node in $nodes) 
{
    $child = $xml.CreateElement("ENV")
    $child.SetAttribute("Id","NewID")
    $child.InnerXML = "New Text"

    $parent = $node.ParentNode
    $parent.InsertAfter($child,$parent.FirstChild)
}


# Results

<#
Id    #text   
--    -----   
NewID New Text
NewID New Text
NewID New Text
NewID New Text
#>

$xml.save('.\test2.xml')
Get-Content -Path '.\test2.xml'

# Results
<#
<ROOT>
  <C1 Id="id1">
    <ENV Id="E1">E1</ENV>
    <ENV Id="NewID">New Text</ENV>
    <ENV Id="E2">E2</ENV>
    <ENV Id="E3">E3</ENV>
    <D1>D1</D1>
    <P1>
      <S1>S1</S1>
      <M1>M1</M1>
      <M2>M2</M2>
    </P1>
  </C1>
  <C2 Id="id2">
    <ENV Id="E1">E1</ENV>
    <ENV Id="NewID">New Text</ENV>
    <ENV Id="E2">E2</ENV>
    <ENV Id="E3">E3</ENV>
    <D1>D1</D1>
    <W1>W1</W1>
  </C2>
  <C3 Id="id3">
    <ENV Id="E1">E1</ENV>
    <ENV Id="NewID">New Text</ENV>
    <ENV Id="E2">E2</ENV>
    <ENV Id="E3">E3</ENV>
    <D1>D1</D1>
  </C3>
  <C4 Id="id4">
    <ENV Id="E1">E1</ENV>
    <ENV Id="NewID">New Text</ENV>
    <ENV Id="E2">E2</ENV>
    <ENV Id="E3">E3</ENV>
    <D1>D1</D1>
  </C4>
</ROOT>
#>

@postanote. Many thanks, I knew I must be doing something silly!

No worries.