使用PowerShell,我想将几个子元素添加到XML树中。
我知道ADD ONE元素,我知道要添加一个或多个属性,但我不明白如何添加几个元素。添加XML子元素
一种方法是write a sub-XML tree as text
但我不能使用这种方法,因为元素不是一次添加的。
要添加一个元素,我这样做:
[xml]$xml = get-content $nomfichier
$newEl = $xml.CreateElement('my_element')
[void]$xml.root.AppendChild($newEl)
工作正常。这给了我这个XML树:
$xml | fc
class XmlDocument
{
root =
class XmlElement
{
datas =
class XmlElement
{
array1 =
[
value1
value2
value3
]
}
my_element = <-- the element I just added
}
}
现在我想添加一个子元素'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)
这给这个XML树(partialy显示):
my_element =
class XmlElement
{
my_sub_element =
another_one =
}
这些都是属性,而不是子元素。
子元素将被显示为这样:
my_element =
[
my_sub_element
another_one
]
问题:如何添加几个子元素,一次一个?
比我迄今为止发现的解决方案要好得多!和更干净。谢谢。 –
这很好。我的问题是,它写了很多东西到控制台上。 调试显示它发生在这一行:$ xmlSubElt.AppendChild($ xmlSubText) 如果我写“> $ null”到最后。其他东西写出来 我可以封锁它吗? – Tomi
用'|替换'> $ null'出null'。 – JPBlanc