Alex Rivera | Logout

What is the best way to compare XML files for equality?

Asked 2008-11-18T17:50:14.840
13

I'm using .NET 2.0, and a recent code change has invalidated my previous Assert.AreEqual call (which compared two strings of XML). Only one element of the XML is actually different in the new codebase, so my hope is that a comparison of all the other elements will give me the result I want. The comparison needs to be done programmatically, since it's part of a unit test.

At first, I was considering using a couple instances of XmlDocument. But then I found this: http://drowningintechnicaldebt.com/blogs/scottroycraft/archive/2007/05/06/comparing-xml-files.aspx

It looks like it might work, but I was interested in Stack Overflow feedback in case there's a better way.

I'd like to avoid adding another dependency for this if at all possible.

Similar questions

Edit
Report

1 Answer

0

I ended up getting the result I wanted with the following code:

private static void ValidateResult(string validationXml, XPathNodeIterator iterator, params string[] excludedElements)
    {
        while (iterator.MoveNext())
        {
            if (!((IList<string>)excludedElements).Contains(iterator.Current.Name))
            {
                Assert.IsTrue(validationXml.Contains(iterator.Current.Value), "{0} is not the right value for {1}.", iterator.Current.Value, iterator.Current.Name);
            }
        }
    }

Before calling the method, I create a navigator on the instance of XmlDocument this way:

XPathNavigator nav = xdoc.CreateNavigator();

Next, I create an instance of XPathExpression, like so:

XPathExpression expression = XPathExpression.Compile("/blah/*");

I call the method after creating an iterator with the expression:

XPathNodeIterator iterator = nav.Select(expression);

I'm still figuring out how to optimize it further, but it does the trick for now.

answered 2008-11-19T23:08:44.853

Your Answer