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

前端 未结 7 1294
春和景丽
春和景丽 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:29

    You might find it's less fragile to parse the XML into an XmlDocument and base your Assert calls on XPath Query. Here are some helper assertion methods that I use frequently. Each one takes a XPathNavigator, which you can obtain by calling CreateNavigator() on the XmlDocument or on any node retrieved from the document. An example of usage would be:

         XmlDocument doc = new XmlDocument( "Testdoc.xml" );
         XPathNavigator nav = doc.CreateNavigator();
         AssertNodeValue( nav, "/root/foo", "foo_val" );
         AssertNodeCount( nav, "/root/bar", 6 )
    
        private static void AssertNodeValue(XPathNavigator nav,
                                             string xpath, string expected_val)
        {
            XPathNavigator node = nav.SelectSingleNode(xpath, nav);
            Assert.IsNotNull(node, "Node '{0}' not found", xpath);
            Assert.AreEqual( expected_val, node.Value );
        }
    
        private static void AssertNodeExists(XPathNavigator nav,
                                             string xpath)
        {
            XPathNavigator node = nav.SelectSingleNode(xpath, nav);
            Assert.IsNotNull(node, "Node '{0}' not found", xpath);
        }
    
        private static void AssertNodeDoesNotExist(XPathNavigator nav,
                                             string xpath)
        {
            XPathNavigator node = nav.SelectSingleNode(xpath, nav);
            Assert.IsNull(node, "Node '{0}' found when it should not exist", xpath);
        }
    
        private static void AssertNodeCount(XPathNavigator nav, string xpath, int count)
        {
            XPathNodeIterator nodes = nav.Select( xpath, nav );
            Assert.That( nodes.Count, Is.EqualTo( count ) );
        }
    

提交回复
热议问题