Skip to content

Instantly share code, notes, and snippets.

@Benrnz
Created February 26, 2009 02:29
Show Gist options
  • Save Benrnz/70601 to your computer and use it in GitHub Desktop.
Save Benrnz/70601 to your computer and use it in GitHub Desktop.
/// <summary>
/// An extension class for XElement. Compare to XElements for equality.
/// </summary>
public static class XElementExtension {
/// <summary>
/// Compares two elements and their descendants contain the same elements and those elements have the same value. Useful for verifying deserialisation. xml attributes are ignored.
/// Order of siblings is also ignored.
/// </summary>
/// <param name="thisValue">The instance of XElement</param>
/// <param name="compareTo">the XElement to compare</param>
/// <returns>true if the are deemed to be the same. Otherwise false.</returns>
public static bool ElementCompare(this XElement thisValue, XElement compareTo) {
return ElementCompare(thisValue, compareTo, "/");
}
private static bool ElementCompare(XElement thisValue, XElement compareTo, string path) {
if (compareTo == null && thisValue == null) {
return true;
}
if (compareTo == null && thisValue != null) {
Logger.Log("{0} not found in deserialisation. (1)", path);
return false;
}
if (thisValue.Name != compareTo.Name) {
Logger.Log("{0} not found in deserialisation. (1)", path);
return false;
}
if (thisValue.IsEmpty != compareTo.IsEmpty) {
Logger.Log("{0} not found in deserialisation. (2)", path);
return false;
}
if (thisValue.HasElements != compareTo.HasElements) {
Logger.Log("{0} not found in deserialisation. (3)", path);
return false;
}
if (!thisValue.HasElements && thisValue.Value != compareTo.Value) {
Logger.Log("{0} not found in deserialisation. (3)", path);
return false;
}
if (thisValue.HasElements) {
for (int index = 0; index < thisValue.Elements().Count(); index++) {
XElement childExpectedElement = thisValue.Elements().ElementAt(index);
XElement childActualElement = null;
if (index < compareTo.Elements().Count()) {
childActualElement = compareTo.Elements().ElementAt(index);
}
if (childActualElement == null || childExpectedElement.Name != childActualElement.Name) { // if sibling elements are out or order
childActualElement = (from x in compareTo.Elements(childExpectedElement.Name) // Get the first one that matches the name. If there are duplicates then they should be in the same order.
select x).FirstOrDefault();
}
string newPath = string.Format(CultureInfo.CurrentCulture, "{0}/{1}[{2}]", path, childExpectedElement.Name, index);
ElementCompare(childExpectedElement, childActualElement, newPath);
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment