Laziness and XML: New-XmlElement

I love structured data.  I love how orderly it is, how logical.  However, I do not like the repetition.  Get the OwnerDoc.  Create an Element.  Loop over a bunch of AddAttribute calls, AppendChild it someplace.  90% of the time, this is how I build my XML structure.  Why not have PowerShell do it?

function New-XmlElement {
    param (
        [hashtable]$attributes = @{},
    if (!$parentElement -or !$ElementName) { return; }
    $element = $parentElement.OwnerDocument.CreateElement($elementName);
    foreach ($key in ($attributes.Keys | Sort-Object)) {
        $element.SetAttribute($key, $attributes[$key]) | Out-Null;
    if ($text) { $element.InnerText = $text; }


Comments (0)

Skip to main content