Skip to content

Instantly share code, notes, and snippets.

@papsl
Created April 12, 2019 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save papsl/a905efafa175c542c605289c8dbe8e21 to your computer and use it in GitHub Desktop.
Save papsl/a905efafa175c542c605289c8dbe8e21 to your computer and use it in GitHub Desktop.
Sorts an XML file by element and attribute names, removes not needed empty tags. Useful for diffing XML files.
<#
.SYNOPSIS Sorts an XML file by element and attribute names, removes not needed empty tags. Useful for diffing XML files.
.NOTES
Original https://danielsmon.com/2017/03/10/diff-xml-via-sorting-xml-elements-and-attributes/
Last change: Peter Pirc (remove empty end tag)
Licence Public domain
#>
param (
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
# The path to the XML file to be sorted
[string]$XmlPath
)
process {
if (-not (Test-Path $XmlPath)) {
Write-Warning "Skipping $XmlPath, as it was not found."
continue;
}
$fullXmlPath = (Resolve-Path $XmlPath)
[xml]$xml = Get-Content $fullXmlPath
Write-Output "Sorting $fullXmlPath"
function SortChildNodes($node, $depth = 0, $maxDepth = 20) {
if ($node.HasChildNodes -and $depth -lt $maxDepth) {
foreach ($child in $node.ChildNodes) {
SortChildNodes $child ($depth + 1) $maxDepth
}
}
$sortedAttributes = $node.Attributes | Sort-Object { $_.Name }
$sortedChildren = $node.ChildNodes | Sort-Object { $_.OuterXml }
$node.RemoveAll()
foreach ($sortedAttribute in $sortedAttributes) {
[void]$node.Attributes.Append($sortedAttribute)
}
foreach ($sortedChild in $sortedChildren) {
if($sortedChild.HasChildNodes -eq $false -and $sortedChild.NodeType -eq [System.Xml.XmlNodeType]::Element){
$sortedChild.IsEmpty=$true
}
[void]$node.AppendChild($sortedChild)
}
}
SortChildNodes $xml.DocumentElement
$xml.Save($fullXmlPath)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment