1
\$\begingroup\$

The purpose of this PowerShell function is to make it simpler to output XML in a given format. For my use case, that XML did not have a schema associated, so I've not implemented any namespace logic; though suspect that could be easily added.

Code

Add-Type -AssemblyName 'System.Xml.Linq'

function Create-XmlElement {
    [CmdletBinding(DefaultParameterSetName = 'ByXMLNodes')]
    param (
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 0)]
        [string]$Name
        ,
        [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'ByXMLNodes', Position = 1)]
        [System.Xml.Linq.XObject[]]$ChildObjects
        ,
        [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'ByValue', Position = 1)]
        [object]$Value
    )
    process {
        (New-Object -TypeName 'System.Xml.Linq.XElement' -ArgumentList ([System.Xml.Linq.XName]$Name), $Value, $ChildObjects)
    }
}

function Create-XmlAttribute { #just use a function for this as there's nothing clever required
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$Name
        , 
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$Value
    )
    process {
        (New-Object -type 'System.Xml.Linq.XAttribute' -ArgumentList ([System.Xml.Linq.XName]$Name), $Value)
    }
}

Example Usage

Set-Alias -Name 'X<>' -Value 'Create-XmlElement'   #added aliases to avoid over cluttering the below definitions
Set-Alias -Name 'X@' -Value 'Create-XmlAttribute'  #hopefully that makes the code a little easier to read
                                                   #I had gone with CXE and CXA, but then figured this notation may be clearer (though possibly risky / more confusing for some?)
(
    X<> 'Root' @(
        (X@ 'attribute1' 'attribute''s value'), 
        (X<> 'hello' 'valuex'),
        (X<> 'hello2' (
            X<> 'aDate' (Get-Date)
        ))
    )
).ToString()

Output

The above example produces this XML:

<Root attribute1="attribute's value">
  <hello>valuex</hello>
  <hello2>
    <aDate>2017-06-09T16:09:27.0538147+01:00</aDate>
  </hello2>
</Root>
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.