With PowerShell, I want to add several sub-elements into an XML tree.
I know to ADD ONE element, I know to add one or several attributes, but I don't understand how to ADD SEVERAL elements.
One way whould be to write a sub-XML tree as text
But I can't use this method because the elements are not added at once.
To add one element, I do that:
[xml]$xml = get-content $nomfichier
$newEl = $xml.CreateElement('my_element')
[void]$xml.root.AppendChild($newEl)
Works fine. This give me this XML tree:
$xml | fc
class XmlDocument
{
root =
class XmlElement
{
datas =
class XmlElement
{
array1 =
[
value1
value2
value3
]
}
my_element = <-- the element I just added
}
}
Now I want to add a sub element to 'my_element'. I use a similar method:
$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)
This give this XML tree (partialy displayed):
my_element =
class XmlElement
{
my_sub_element =
another_one =
}
Those are attributes, not sub-elements.
Sub-elements would be displayed as this:
my_element =
[
my_sub_element
another_one
]
Question: How do I add several sub-elements, one at a time?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…