xml PowerShell:如何将 XmlElement 添加到非根元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3041489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PowerShell: How to add XmlElement to a non-root element
提问by Ariel
I'm having trouble adding an XmlElement to a non-root element in PowerShell.
我在 PowerShell 中将 XmlElement 添加到非根元素时遇到问题。
Basically, given this xml:
基本上,鉴于此 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</field>
<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?
我错过了什么?
回答by Martin Hollingsworth
Try using the AppendChildmethod on the appropriate element. There are alternatives to AppendChild as described in Create New Nodes in the DOMwhich allow you more control of the location in the DOM tree.
尝试在适当的元素上使用AppendChild方法。在 DOM中创建新节点中描述了 AppendChild 的替代方法,它允许您更好地控制 DOM 树中的位置。
$club = $xml.CreateElement('club')
$club.SetAttribute('name','barracas')
$xml.clubs.AppendChild($club)

