Xml – adding XML sub-elements


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')

Works fine. This give me this XML tree:

$xml | fc
class XmlDocument
  root =
    class XmlElement
      datas =
        class XmlElement
          array1 =
      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')

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 =

Question: How do I add several sub-elements, one at a time?

Best Solution

Have a look to the following example :

# Document creation
[xml]$xmlDoc = New-Object system.Xml.XmlDocument
$xmlDoc.LoadXml("<?xml version=`"1.0`" encoding=`"utf-8`"?><Racine></Racine>")

# Creation of a node and its text
$xmlElt = $xmlDoc.CreateElement("Machine")
$xmlText = $xmlDoc.CreateTextNode("Mach1")

# Creation of a sub node
$xmlSubElt = $xmlDoc.CreateElement("Adapters")
$xmlSubText = $xmlDoc.CreateTextNode("Network")

# Creation of an attribute in the principal node
$xmlAtt = $xmlDoc.CreateAttribute("IP")
$xmlAtt.Value = ""

# Add the node to the document

# Store to a file 


Remark : Using a relative path in Save will not do what you expect.

Related Question