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 (
[System.Xml.XmlElement]$parentElement,
[string]$elementName,
[hashtable]$attributes = @{},
[string]$text
);
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; }
$parentElement.AppendChild($element);
}