Skip to content

Instantly share code, notes, and snippets.

@smitmartijn
Created February 20, 2025 16:28
Show Gist options
  • Save smitmartijn/ec9c08c0bda55c649b5242d1cfb90116 to your computer and use it in GitHub Desktop.
Save smitmartijn/ec9c08c0bda55c649b5242d1cfb90116 to your computer and use it in GitHub Desktop.
function Compare-XmlContent {
param (
[Parameter(Mandatory=$true)]
[string]$FirstXml,
[Parameter(Mandatory=$true)]
[string]$SecondXml,
[Parameter(Mandatory=$false)]
[switch]$IgnoreWhitespace,
[Parameter(Mandatory=$false)]
[switch]$IgnoreAttributes,
[Parameter(Mandatory=$false)]
[switch]$IgnoreComments
)
function Format-XmlString {
param ([string]$XmlString)
try {
$xmlDoc = [System.Xml.XmlDocument]::new()
$xmlDoc.LoadXml($XmlString)
if ($IgnoreComments) {
$comments = $xmlDoc.SelectNodes("//comment()")
foreach ($comment in $comments) {
$comment.ParentNode.RemoveChild($comment)
}
}
if ($IgnoreAttributes) {
$elements = $xmlDoc.SelectNodes("//*[@*]")
foreach ($element in $elements) {
while ($element.Attributes.Count -gt 0) {
$element.RemoveAttribute($element.Attributes[0].Name)
}
}
}
$stringWriter = [System.IO.StringWriter]::new()
$xmlWriter = [System.Xml.XmlTextWriter]::new($stringWriter)
$xmlWriter.Formatting = [System.Xml.Formatting]::Indented
$xmlDoc.WriteTo($xmlWriter)
$formattedXml = $stringWriter.ToString()
if ($IgnoreWhitespace) {
$formattedXml = $formattedXml -replace '>\s+<', '><'
$formattedXml = $formattedXml.Trim()
}
return $formattedXml
}
catch {
throw "Error formatting XML: $_"
}
finally {
if ($null -ne $xmlWriter) { $xmlWriter.Close() }
if ($null -ne $stringWriter) { $stringWriter.Close() }
}
}
try {
$formattedFirst = Format-XmlString -XmlString $FirstXml
$formattedSecond = Format-XmlString -XmlString $SecondXml
$comparison = Compare-Object `
-ReferenceObject ($formattedFirst -split "`n") `
-DifferenceObject ($formattedSecond -split "`n") `
-IncludeEqual
$result = @{
AreEqual = ($comparison | Where-Object SideIndicator -ne "==").Count -eq 0
Differences = @()
}
foreach ($diff in $comparison) {
if ($diff.SideIndicator -ne "==") {
$result.Differences += [PSCustomObject]@{
Line = $diff.InputObject.Trim()
Type = switch ($diff.SideIndicator) {
"<=" { "Only in First XML" }
"=>" { "Only in Second XML" }
}
}
}
}
return $result
}
catch {
throw "Error comparing XML: $_"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment