Hi,
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 $xmlDoc.LoadXml("") $datacenters = Get-Datacenter # foreach ($datacenter in $datacenters) { $datacentername = $datacenter.name #region datacenter loop $datacentreelement = $xmlDoc.CreateElement("computer") $node =$xmlDoc.Audithardware.OU.AppendChild($datacenterelement) $node.setattribute("Vrt", "Data Center") $node.setattribute("Name", "$datacentername") #endregion }
//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.