Private/Add-XmlChildElement.ps1

# Copyright 2019 David Haymond.
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.

function Add-XmlChildElement {
    [CmdletBinding()]
    [OutputType($null, [System.Xml.XmlNode])]
    param (
        [Parameter(
            Mandatory = $true,
            Position = 0
        )]
        [System.Xml.XmlNode] $Parent,

        [Parameter(
            Mandatory = $true,
            Position = 1
        )]
        [string] $Name,

        [Parameter(
            Position = 2
        )]
        [string] $InnerText,

        [string] $NamespaceUri,

        [switch] $PassThru
    )
    if (!$NamespaceUri) {
        $NamespaceUri = $Parent.NamespaceURI
    }
    if ($Parent -is [System.Xml.XmlDocument]) {
        $document = $Parent
    }
    else {
        $document = $Parent.OwnerDocument
    }
    $child = $document.CreateElement($Name, $NamespaceUri)
    if ($InnerText) {
        $child.InnerText = $InnerText
    }
    $Parent.AppendChild($child) | Out-Null
    if ($PassThru) {
        $child
    }
}