Last active
October 7, 2024 19:46
-
-
Save ctigeek/3726bb02055d0558fdd9cd3ffb292dbf to your computer and use it in GitHub Desktop.
Powershell - Compare two XML documents.
This file contains hidden or 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
function Compare-XmlDocs($actual, $expected) { | |
if ($actual.Name -ne $expected.Name) { | |
throw "Actual name not same as expected: actual=" + $actual.Name | |
} | |
##attributes... | |
if ($actual.Attributes.Count -ne $expected.Attributes.Count) { | |
throw "attribute mismatch for actual=" + $actual.Name | |
} | |
for ($i=0;$i -lt $expected.Attributes.Count; $i =$i+1) { | |
if ($expected.Attributes[$i].Name -ne $actual.Attributes[$i].Name) { | |
throw "attribute name mismatch for actual=" + $actual.Name | |
} | |
if ($expected.Attributes[$i].Value -ne $actual.Attributes[$i].Value) { | |
throw "attribute value mismatch for actual=" + $actual.Name | |
} | |
} | |
##children | |
if ($expected.ChildNodes.Count -ne $actual.ChildNodes.Count) { | |
throw "child node mismatch. for actual=" + $actual.Name | |
} | |
for ($i=0;$i -lt $expected.ChildNodes.Count; $i =$i+1) { | |
if (-not $actual.ChildNodes[$i]) { | |
throw "actual missing child nodes. for actual=" + $actual.Name | |
} | |
Compare-XmlDocs $actual.ChildNodes[$i] $expected.ChildNodes[$i] | |
} | |
if ($expected.InnerText) { | |
if ($expected.InnerText -ne $actual.InnerText) { | |
throw "inner text mismatch for actual=" + $actual.Name | |
} | |
} | |
elseif ($actual.InnerText) { | |
throw "actual has inner text but expected does not for actual=" + $actual.Name | |
} | |
} |
Fixed. Thanks!!
This is very useful for comparing two files with the same structure, have you ever written anything which can compare two XML files with both changes in attributes and structure i.e. nodes added/removed.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very useful - thanks for posting! - but in line 28 did you really mean to have the parameters in reverse? i.e., Compare-XmlDocs $actual.ChildNodes[$i] $expected.ChildNodes[$i]
They don't match up with the order of parameters for the function