【问题标题】:PowerShell: How to add XmlElement to a non-root elementPowerShell:如何将 XmlElement 添加到非根元素
【发布时间】:2011-03-03 18:13:22
【问题描述】:

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

基本上,给定这个 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.

我错过了什么?

【问题讨论】:

    标签: xml powershell


    【解决方案1】:

    尝试在适当的元素上使用 AppendChild 方法。如Create New Nodes in the DOM 中所述,AppendChild 有其他替代方法,可让您更好地控制 DOM 树中的位置。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多