5

Is there a simple way to compare two XML structures to determine if they have the same structure and data?

I have a function that returns an XmlNode and I am trying to write unit tests for it. I store the correct XML result in a file. Durring the test I load the file into an XmlDocument, locate the proper XmlNode and compare against the result of the function. A straight compare does not work (as expected) and InnerXml does not work either. I am considering removing all whitespace from InnerXml and comparing that, or writing my own compare to walk the tree, but I don't like either option much.

oillio
  • 4,748
  • 5
  • 31
  • 37

3 Answers3

8

XNode.DeepEquals. Read the caveats before using it.

Srikar Doddi
  • 15,499
  • 15
  • 65
  • 106
  • 1
    The question is about `XmlDocument`/`XmlNode`, not about LINQ to XML. – Pavel Minaev Aug 21 '09 at 19:49
  • 1
    To be precise, his question is about comparing XML structures. His problem is with his approach (using XmlDocument). I agree with CodeToGlory: XNode.DeepEquals. – Ed Power Aug 21 '09 at 19:55
2

Like CodeToGlory answered, XNode.DeepEquals() might fit your bill, check the remarks section on the MSDN page.

If you are stuck with XmlDocument (instead of XDocument), the answer is: No, there is no simple (existing way) to do it. XmlNode does not override Equals(), or provide an alternative. But it is not impossible to write, and that same Remarks section can be used as a starting point for a tree-walk algorithm.

Do get a clear picture of your requirements first, concerning Attributes, comments, CDATA nodes etc.

H H
  • 263,252
  • 30
  • 330
  • 514
2

If you must use XmlDocument and its supporting types, consider using Microsoft's XmlDiffPatch, which performs customizable diff-operations on XML data structures.

Steve Guidi
  • 19,700
  • 9
  • 74
  • 90