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
andxmlns: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.
I am using ExamXML for comparing XML files. You can try it. The authors, A7Soft, also provide API for comparing XML files
Another way to do this would be -
This won't give you the exact location of the difference, but if you just want to know if there is a difference, this is easy to do without any third party libraries.
Not relevant for the OP since it currently ignores child order, but if you want a code only solution you can try XmlSpecificationCompare which I somewhat misguidedly developed.
For comparing two XML outputs in automated testing I found
XNode.DeepEquals
.Usage:
Reference: https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.xnode.deepequals?view=netcore-2.2
https://github.com/CameronWills/FatAntelope Another alternative library to the Microsoft XML Diff API. It has a XML diffing algorithm to do an unordered comparison of two XML documents and produce an optimal matching.
It is a C# port of the X-Diff algorithm described here: http://pages.cs.wisc.edu/~yuanwang/xdiff.html
Disclaimer: I wrote it :)
I googled up a more complete list of solutions of this problem today, I am going to try one of them soon: