Skip to content

Instantly share code, notes, and snippets.

@ctigeek
Last active July 5, 2023 21:01
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ctigeek/3726bb02055d0558fdd9cd3ffb292dbf to your computer and use it in GitHub Desktop.
Save ctigeek/3726bb02055d0558fdd9cd3ffb292dbf to your computer and use it in GitHub Desktop.
Powershell - Compare two XML documents.
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
}
}
@dgapinski
Copy link

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

@ctigeek
Copy link
Author

ctigeek commented Aug 4, 2019

Fixed. Thanks!!

@Kalabia
Copy link

Kalabia commented Jul 5, 2023

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