Created
April 12, 2019 09:01
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.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