2010-06-14 33 views
11

我在將XmlElement添加到PowerShell中的非根元素時遇到問題。PowerShell:如何將XmlElement添加到非根元素

基本上,鑑於此xml:

<clubs> 
     <club name="boca" position="1"> 
       <field>bombonera</field> 
       <field>bombonerita</field> 
     </club> 
     <club name="racing" position="19"> 
       <field>cilindro</field> 
     </club> 
</clubs> 

我想要實現這個

<clubs> 
     <club name="boca" position="1"> 
       <field>bombonera</field> 
       <field>bombonerita</field> 
     </club> 
     <club name="racing" position="19"> 
       <field>cilindro</field> 
     </club> 
     <club name="barracas" /> 
</clubs> 

我創建一個元素,

$new = $clubs.CreateElement("barracas") 

當我嘗試這個元素添加到非根節點即

$clubs.clubs.club += $new 

我得到

Cannot set "club" because only strings can be used as values to set XmlNode properties. 

我缺少什麼?

回答

23

嘗試在適當的元素上使用AppendChild方法。如Create New Nodes in the DOM中所述,可以使用AppendChild的替代方法,它們允許您更多地控制DOM樹中的位置。

$club = $xml.CreateElement('club') 
$club.SetAttribute('name','barracas') 
$xml.clubs.AppendChild($club)