使用PowerShell,我想在XML树中添加几个子元素.
我知道添加一个元素,我知道添加一个或几个属性,但我不明白如何添加几个元素.
一种方法是对子级来写一个子XML树作为文本
但是因为元素没有立即加入,我不能用这种方法.
要添加一个元素,我这样做:
[xml]$xml = get-content $nomfichier
$newEl = $xml.CreateElement('my_element')
[void]$xml.root.AppendChild($newEl)
Run Code Online (Sandbox Code Playgroud)
工作良好.这给了我这个XML树:
$xml | fc
class XmlDocument
{
root =
class XmlElement
{
datas =
class XmlElement
{
array1 =
[
value1
value2
value3
]
}
my_element = <-- the element I just added
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想在'my_element'中添加一个子元素.我使用类似的方法:
$anotherEl = $xml.CreateElement('my_sub_element')
[void]$xml.root.my_element.AppendChild($anotherEl) <-- error because $xml.root.my_element is a string
[void]$newEl.AppendChild($anotherEl) <-- ok
$again = $xml.CreateElement('another_one')
[void]$newEl.AppendChild($again)
Run Code Online (Sandbox Code Playgroud)
这给了这个XML树(部分显示):
my_element =
class XmlElement
{
my_sub_element =
another_one =
}
Run Code Online (Sandbox Code Playgroud)
这些是属性,而不是子元素. …