Iterating through a loop and adding elements to a node

I have defined some XML Text and cast it as XML type. I also have a variable that has some objects in this case VMWare Datacentres using PowerCLI… i would like to add elements based on the number of objects.

Snippet of Code is below:

[xml]$xmlDoc = New-Object system.Xml.XmlDocument

$datacenters = Get-Datacenter

foreach ($datacenter in $datacenters)
	$datacentername = $
	#region datacenter loop
	$datacentreelement = $xmlDoc.CreateElement("computer")
        $node =$xmlDoc.Audithardware.OU.AppendChild($datacenterelement)
	$node.setattribute("Vrt", "Data Center")
	$node.setattribute("Name", "$datacentername")

//Apologies some text is in the XML string
I thought by doing it this way I would be able to constantly add on an element to that node in the XML. However when I try to do this in the loop I get an error message

Exception calling "AppendChild" with "1" argument(s): "The node to be inserted is from a different document context."
At line:7 char:5
+     $node =$xmlDoc.Audithardware.OU.AppendChild($datacenterelement)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

I have debugged it and it seems that it is failing on this line;

$node =$xmlDoc.Audithardware.OU.AppendChild($datacenterelement). Does any one know of a way to iterate through a loop (in this case datacenters) so that I can add a new element to the node? I would also like to add attributes to it but I want to try doing that myself.

I would be grateful for any direction. I have been reading posts online but they dont talk about this particular circumstance.

seens you incorrectly show your context.

if you have xml inside, use gist
minimal example works ok

PS C:\> [xml]$xmlDoc = New-Object system.Xml.XmlDocument
>> $xmlDoc.LoadXml("[root][node]text[/node][/root]") # brackets changed
PS C:\> 1..2 | foreach { $e = $xmlDoc.CreateElement('computer'); $xmlDoc.root.AppendChild($e) | Out-Null }
PS C:\> $xmlDoc.root

node computer
---- --------
text {, }

Thanks for the help , I found out the reason why it wasn’t working I was passing it the wrong variable. It worked. Thank you.