How would you compare two XML Documents?

Neil C. Obremski picture Neil C. Obremski · Oct 3, 2008 · Viewed 86.8k times · Source

As part of the base class for some extensive unit testing, I am writing a helper function which recursively compares the nodes of one XmlDocument object to another in C# (.NET). Some requirements of this:

  • The first document is the source, e.g. what I want the XML document to look like. Thus the second is the one I want to find differences in and it must not contain extra nodes not in the first document.
  • Must throw an exception when too many significant differences are found, and it should be easily understood by a human glancing at the description.
  • Child element order is important, attributes can be in any order.
  • Some attributes are ignorable; specifically xsi:schemaLocation and xmlns:xsi, though I would like to be able to pass in which ones are.
  • Prefixes for namespaces must match in both attributes and elements.
  • Whitespace between elements is irrelevant.
  • Elements will either have child elements or InnerText, but not both.

While I'm scrapping something together: has anyone written such code and would it be possible to share it here?

On an aside, what would you call the first and second documents? I've been referring to them as "source" and "target", but it feels wrong since the source is what I want the target to look like, else I throw an exception.

Answer

Danimal picture Danimal · Oct 3, 2008

Microsoft has an XML diff API that you can use.

Unofficial NuGet: https://www.nuget.org/packages/XMLDiffPatch.