private/ConvertTo-XmlTag.ps1
|
function ConvertTo-XmlTag { <# .SYNOPSIS Converts a value into an XML tag string, with configurable handling of empty content. .DESCRIPTION Wraps $Value in an XML tag named $TagName, applying the encoding style given by $EncodingStyle. Supports true/false/null normalization via -IsTrueFalseNull and truncation via -MaxLen. An empty $Value ('') and the "intentionally blank" marker ('.') are both treated as "no value" and resolved via $DefaultValue: - $DefaultValue not bound (default): no tag is emitted. - $DefaultValue = '': an empty tag is forced, e.g. '<TagName></TagName>'. - $DefaultValue = any other string: that value is used as the tag's content, run through the same encoding as regular content. #> [CmdletBinding()] param ( # Name of the XML tag to generate. [Parameter(Mandatory, Position = 0)] [string] $TagName, # Raw value to encode and wrap in the tag. [Parameter(Position = 1)] [string] $Value, # Encoding style applied to $Value and, when used, to $DefaultValue. [Parameter(Position = 2)] [ValidateSet('Salesforce', 'Url', 'Xml')] [string] $EncodingStyle = 'Xml', [Parameter()] [switch] $IsTrueFalseNull, # Fallback used when Value is empty or '.'. See .DESCRIPTION for the three cases. [Parameter()] [string] $DefaultValue, [Parameter()] [int] $MaxLen ) $ErrorActionPreference = 'Stop' [bool] $IsDebug = $DebugPreference -ne 'SilentlyContinue' [bool] $IsVerbose = $VerbosePreference -ne 'SilentlyContinue' $Value = $Value.Trim() if ($MaxLen -and ($Value.Length -gt $MaxLen)) { $Value = $Value.SubString(0, $MaxLen).Trim() } # Resolves the "no value given" case ('' or '.') via $DefaultValue: # not bound -> no tag; '' -> forced empty tag; anything else -> tag with that (encoded) content. function EmptyValueTag { if ($null -eq $DefaultValue) { return '' } if ($DefaultValue -eq '') { return "<$TagName></$TagName>" } return "<$TagName>$(ConvertTo-EncodedString $DefaultValue $EncodingStyle)</$TagName>" } function TrueValueTag { return "<$TagName>true</$TagName>" } function FalseValueTag { return "<$TagName>false</$TagName>" } if ($IsTrueFalseNull) { $xml = switch ($Value) { 'X' { TrueValueTag } '--' { FalseValueTag } '-' { FalseValueTag } 'true' { TrueValueTag } 'false' { FalseValueTag } '.' { EmptyValueTag } '' { EmptyValueTag } Default { '' } } } else { $xml = switch ($Value) { '.' { EmptyValueTag } '' { EmptyValueTag } Default { "<$TagName>$(ConvertTo-EncodedString $Value $EncodingStyle)</$TagName>" } } } return $xml } |