Append data into existing xml file via powershell

早过忘川 提交于 2019-12-10 22:14:17

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/13751230/append-data-into-existing-xml-file-via-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!