I have a scenario where I need to chain nest XmlElements, and I got a working solution using a recursive function, but I can't help but feel that it can be made better.
Here's my code so far:
function AppendChild
{
param
(
[string[]]$string,
$obj,
[System.Xml.XmlDocument]$XML
)
if ($string.Length -gt 0)
{
$child = $XML.CreateElement($string[0])
$child.InnerText = ""
AppendChild -string ($string | Select -Skip 1) -obj $child -XML $XML
$obj.AppendChild($child)
}
}
$string = "this is a somewhat long string" -split " "
$XML = New-Object System.Xml.XmlDocument
$root = $XML.CreateElement($string[0])
AppendChild -string ($string | Select -Skip 1) -obj $root -XML $XML
$root.OuterXml # <this><is><a><somewhat><long><string></string></long></somewhat></a></is></this>
Any suggestions?
[System.Xml.XmlDocument]::new()
. Is that a new feature in PowerShell? \$\endgroup\$ – Dangph Apr 29 '16 at 0:08