PowerShell:如何将 XmlElement 添加到非根元素 [英] PowerShell: How to add XmlElement to a non-root element

查看:44
本文介绍了PowerShell:如何将 XmlElement 添加到非根元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 PowerShell 中将 XmlElement 添加到非根元素时遇到问题.

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

基本上,给定这个 xml:

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>

我想实现这个

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

当我尝试将此元素添加到非根节点时,即

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

$clubs.clubs.club += $new

我明白

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

我错过了什么?

推荐答案

尝试在适当的元素上使用 AppendChild 方法.如 在 DOM 中创建新节点 中所述,有 AppendChild 的替代方案,其中允许您更好地控制 DOM 树中的位置.

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)

这篇关于PowerShell:如何将 XmlElement 添加到非根元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆