Append data into existing xml file via powershell

13,377

It should be something along the lines of this:

$GroupList = @{"Mickey" = "mouse";"Minnie" = "mouse";"Goofy" = "dog"}

$xml=[xml](get-content .\yourfile.xml)
$xml | Select-Xml -XPath '/agentList/newAgent/agentData' | foreach-object{$_.node.removeall()} #clear group section
$groupNode = $xml.createelement("group")

foreach ($description in $($GroupList.keys))
{
    $descNode = $xml.createelement("description")
    $descNode.setattribute("value",$description)
    $groupNode.appendchild($descNode)

    $valueNode = $xml.createelement("value")
    $valueNode.setattribute("value",$GroupList[$description])
    $groupNode.appendchild($valueNode)
}

$xml.selectsinglenode("agentList/newAgent/agentData").appendchild($groupNode)
$xml.save("C:\YourPathHere\test.xml")

** This code assumes that the "group" element is already existing in ".\yourfile.xml".

Share:
13,377

Related videos on Youtube

Santos
Author by

Santos

I'm a complete tech geek... I love computers, networks, and systems... I'm one of those that need to know how things work on the inside.... so many broken toys as a kid...

Updated on June 04, 2022

Comments

  • Santos
    Santos almost 2 years

    Can I have some help to add nodes into an existing XML using powershell?

    Here is what I have:

    <agentList>
     <newAgent>
          <name>Justice, Kari</name>
          <mu>4690</mu>
      <agentData>
       <group>
           <description>GROUP_DESCRIPTION</description><value>GROUP_NAME</value>
       </group>
      </agentData>
     </newAgent>
    </agentList>
    

    and I need to add this:

      <group><description>ACSR System Logon</description><value></value></group>
      <group><description>Current Call Type</description><value></value></group>
      <group><description>OMS</description><value></value></group>
      <group><description>RIO Log-in</description><value></value></group>
      <group><description>Site</description><value></value></group>
    

    Here:

    <agentList>
     <newAgent>
          <name>Justice, Kari</name>
          <mu>4690</mu>
      <agentData>
       <group>
           <description>GROUP_DESCRIPTION</description><value>GROUP_NAME</value>
               <====== HERE
               <====== HERE
               <====== HERE
               <====== HERE
       </group>
      </agentData>
     </newAgent>
    </agentList>
    

    I may have more than one user on the XML so I was thinking to use the FOREACH line.. but im kinda lost using xml in powershell... If anyone can share some Idea I will be pleased to play with it...