8

I have a few unit tests where I need to make sure that XML generated by a method contains the same elements/values as an expected Xml document.

I used xmlunit in Java, and although they have a .net version it doesn't seem to support namespaces. Are there any alternatives within .net for doing this?

As long as I can just compare 2 Xml strings and get a true/false result to tell me if they match as far as the data contained is concerned I am happy...

4 Answers4

7

I've usually found that XNode.DeepEquals is sufficient for my needs. It's part of the BCL, so no download is required.

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
3

Try Microsoft.XmlDiffPatch:

static public bool IsXmlEqual( XmlReader x1, XmlReader x2,
    bool IgnoreChildOrder, bool IgnoreComments, bool IgnorePI, bool IgnoreWhitespace,
    bool IgnoreNamespaces, bool IgnorePrefixes, bool IgnoreXmlDecl, bool IgnoreDtd
)
{
    XmlDiffOptions options = XmlDiffOptions.None;
    if (IgnoreChildOrder) options |= XmlDiffOptions.IgnoreChildOrder;
    if (IgnoreComments) options |= XmlDiffOptions.IgnoreComments;
    if (IgnorePI) options |= XmlDiffOptions.IgnorePI;
    if (IgnoreWhitespace) options |= XmlDiffOptions.IgnoreWhitespace;
    if (IgnoreNamespaces) options |= XmlDiffOptions.IgnoreNamespaces;
    if (IgnorePrefixes) options |= XmlDiffOptions.IgnorePrefixes;
    if (IgnoreXmlDecl) options |= XmlDiffOptions.IgnoreXmlDecl;
    if (IgnoreDtd) options |= XmlDiffOptions.IgnoreDtd;

    XmlDiff xmlDiff = new XmlDiff(options);
    bool bequal = xmlDiff.Compare(x1, x2, null);
    return bequal;
}
Nestor
  • 13,706
  • 11
  • 78
  • 119
1

Something to keep in mind about MSXML XMLDiff is that if you are comparing very large XML documents be sure your XMLDiff.Algorithm is not set to "Precise" or you will potentially run out of memory. By default its set to Auto which is a safe choice as the API will choose whether to use Precise or Fast based on the file size, number of detected differences and other factors. Here is a good read for the more technically inclined:

http://treepatch.sourceforge.net/report.pdf

Echilon
  • 10,064
  • 33
  • 131
  • 217
Noonway
  • 11
  • 3
0

I have used MS's XMLDiff is the past, but preferred to use Beyond Compare 3's as it has better GUI and batch processing feature (doenst have .NET API though).

for your testing, use XNode.DeepEquals or InnerXML to compare string based representation

Bek Raupov
  • 3,782
  • 3
  • 24
  • 42