PowerShell Insert xml node at the top

Viewed 195

I would like to insert a xml node at the top of other existing child nodes.

The problem with my code is it appends to the bottom.

I tried InsertBefore() but I keep getting errors

Ex:

<Providers>
               <----I want to insert a provider here
  <provider>
    <id>87585857587</id>
    <type>AD</type>
    <name>Demo1</name>
    <event>saga</event>
    <username></username>
    <item>NEV</item>
    <password></password>
  </provider>
</Providers>

My code:

    $varGorup = @{"type"="AD";"name"="DEMO";"event"="DNS";"username"="user1";"item"="store";"password"="password1";}

    $file = [XML](Get-Content $xmlFile)

    $providerNode = $file.providers.AppendChild($file.CreateElement("provider"))

    $varGorup | % getEnumerator | % {
     
        $childNode = $providerNode.AppendChild($file.CreateElement($_.key))
        $childNode.AppendChild($file.CreateTextNode($_.value)) | Out-Null
    }
    
    $file.save($xmlFile)

I tried:

   $file =  [XML](Get-Content $xmlFile) 

    $providers = $file.SelectSingleNode('/providers') 

    $provider  = $file.CreateElement("provider")

    $file.InsertBefore($provider,$providers)

but get this error

Exception calling "InsertBefore" with "2" argument(s): "This document already has a 'DocumentElement' node."
1 Answers

Use the syntax InsertBefore:

$xmlfile ="C:\test.xml"
$xml = [XML](Get-Content $xmlFile)

$varGorup = @{"type"="AD";"name"="DEMO";"event"="DNS";"username"="user1";"item"="store";"password"="password1";}

#calcul the number of node, if total is 0 do an AppendChild, else do that
$total = $xml.Providers.ChildNodes.Count
        
if($total -eq 0){
     $providerNode = $file.providers.AppendChild($xml.CreateElement("provider"))      
} else{
    $providerNode = $xml.providers.InsertBefore($xml.CreateElement("provider"), $xml.Providers.ChildNodes[0])
}

$varGorup | % getEnumerator | % {
     
        $childNode = $providerNode.AppendChild($xml.CreateElement($_.key))
        $childNode.AppendChild($xml.CreateTextNode($_.value)) | Out-Null
    }
 $xml.save($xmlFile)
Related