2012-12-06 35 views
2

我可以通過使用powershell將節點添加到現有的XML中嗎?通過powershell將數據追加到現有的xml文件

以下是我有:

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

,我需要補充一點:

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

這裏:

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

我可以有一個以上的用戶對XML所以我想使用FOREACH行..但我有點在PowerShell中使用xml丟失...如果任何人都可以分享一些想法,我會很高興玩它...

回答

4

應該沿着這一線的東西:

$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") 

**此代碼假定「組」元素已經存在的「 \ yourfile.xml」。

+0

像在通用代碼之前添加$ grouplist? – Santos

+0

我更新了我的答案並測試了代碼,並確保它可以正常工作。 – D3vtr0n

+0

@Santos做了這項工作? – D3vtr0n