Append data into existing xml file via powershell

Santos picture Santos · Dec 6, 2012 · Viewed 12.8k times · Source

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...

Answer

D3vtr0n picture D3vtr0n · Dec 6, 2012

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".