Skip to content

Instantly share code, notes, and snippets.

@swbbl
Created November 15, 2022 04:32
Show Gist options
  • Save swbbl/d8b7bf30eca3c18a75aba3090ac2b84a to your computer and use it in GitHub Desktop.
Save swbbl/d8b7bf30eca3c18a75aba3090ac2b84a to your computer and use it in GitHub Desktop.
Import XML files using the encoding of the XML declaration (if specified) using XmlReader and XmlDocument
function Import-Xml {
[CmdletBinding(DefaultParameterSetName='Path')]
param(
[Parameter(ParameterSetName='Path', Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[string[]]
$Path,
[Parameter(ParameterSetName='LiteralPath', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias('PSPath', 'LP')]
[ValidateNotNullOrEmpty()]
[string[]]
$LiteralPath,
[Parameter()]
[System.Xml.XmlReaderSettings]
$Settings,
[Parameter()]
[switch]
$PreserveWhitespace
)
begin {
if (-not $PSBoundParameters.ContainsKey('Settings')) {
$Settings = [System.Xml.XmlReaderSettings]::new()
}
}
process {
[string[]]$xmlFilePaths = if ($null -ne $LiteralPath) {
# ensures proper paths
Microsoft.PowerShell.Management\Resolve-Path -LiteralPath $LiteralPath
} else {
# expand paths with wildcard characters
Microsoft.PowerShell.Management\Resolve-Path -Path $Path
}
#! To check streaming:
# https://docs.microsoft.com/en-us/dotnet/standard/linq/stream-xml-fragments-xmlreader
# https://docs.microsoft.com/en-us/dotnet/standard/linq/linq-xml-vs-xml-technologies
foreach ($xmlFilePath in $xmlFilePaths) {
try {
$xmlReader = [System.Xml.XmlReader]::Create($xmlFilePath, $Settings)
$xmlDocument = [System.Xml.XmlDocument]::new()
$xmlDocument.PreserveWhitespace = $PreserveWhitespace
$xmlDocument.Load($xmlReader)
$xmlDocument
} catch {
# add some details to exception. ErrorDetails take automatically precedence for 'ToString()'
$errorDetails = '["{0}"] {1}' -f $xmlFilePath, $_.ToString()
$_.ErrorDetails = [System.Management.Automation.ErrorDetails]::new($errorDetails)
# re-throw exception
Write-Error -ErrorRecord $_
} finally {
$xmlReader.Close()
$xmlReader.Dispose()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment