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

前端 未结 7 1252
春和景丽
春和景丽 2020-12-20 12:59

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

7条回答
  •  囚心锁ツ
    2020-12-20 13:30

    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)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.

提交回复
热议问题