Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
}
}
@ashembers

This comment has been minimized.

Copy link

@ashembers ashembers commented Aug 1, 2019

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

This comment has been minimized.

Copy link
Owner Author

@ctigeek ctigeek commented Aug 4, 2019

Fixed. Thanks!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.