开发者

PowerShell: How to add XmlElement to a non-root element

开发者 https://www.devze.com 2023-01-03 05:57 出处:网络
I\'m having trouble adding an XmlElement to a non-root element in PowerShell. Basically, given this xml:

I'm having trouble adding an XmlElement to a non-root element in PowerShell.

Basically, given this xml:

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

I want to achieve this

<clubs> 
        <club name="boca" position="1"> 
                <field>bombonera</fiel开发者_运维问答d> 
                <field>bombonerita</field> 
        </club> 
        <club name="racing" position="19"> 
                <field>cilindro</field> 
        </club> 
        <club name="barracas" />
</clubs>

I create an element,

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

When I try to add this element to a non-root node i.e.

$clubs.clubs.club += $new

I get

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

What am I missing?


Try using the AppendChild method on the appropriate element. There are alternatives to AppendChild as described in Create New Nodes in the DOM which allow you more control of the location in the DOM tree.

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

精彩评论

暂无评论...
验证码 换一张
取 消