我必须比较 XML 中的两个文件,其中我需要显示文件之间“不匹配模式”的内容,无论是节点名称还是节点值的差异。
到目前为止我写的代码是
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
namespace ConsoleApplication1
{
   public class Program
    {
        public Program()
        {
            XmlDocument _mxml1 = new XmlDocument();
            _mxml1.Load(@"C:\Users\Rahul\Documents\xml work\abcd.xml");
            XmlDocument _mxml2 = new XmlDocument();
            _mxml2.Load(@"C:\Users\Rahul\Documents\xml work\efg.xml");
            XmlElement _melement1 = _mxml1.DocumentElement;
            XmlElement _melement2 = _mxml2.DocumentElement;
            XPathNavigator nav1 = _mxml1.CreateNavigator();
            XPathNavigator nav2 = _mxml2.CreateNavigator();
            if (_melement1.HasChildNodes && _melement2.HasChildNodes && _melement1.ChildNodes.Count == _melement2.ChildNodes.Count)
            {
                XmlNodeList _node1 = _melement1.ChildNodes;
                XmlNodeList _node2 = _melement2.ChildNodes;
                foreach (XmlNode _n1 in _node1)
                {
                    foreach (XmlNode _n2 in _node2)
                    {
                        int count = _n1.ChildNodes.Count;
                        int count2 = _n2.ChildNodes.Count;
                        if (_n1.Name.ToString() == _n2.Name.ToString())
                        {
                            int res = _n1.OuterXml.CompareTo(_n2.OuterXml);
                            if (res == 1)
                            {
                                Console.WriteLine("All the child names match for the case ");
                            }
                            if (_n1.InnerText.ToString() != _n2.InnerText.ToString())
                            {
                                Console.WriteLine("Values of some child doesnot match");
                                // here we need to traverse through child nodes of both xmls to find out the change in file..
                            }
                            if (_n1.InnerXml.ToString() == _n2.InnerXml.ToString())
                            {
                                Console.WriteLine("Records match completly");
                            }
                        }
                        else
                        {
                            Console.WriteLine("XML_1 " + "     " + "" + "XML_2  \n" + _n1.Name + " " + _n2.Name);
                        }
                    }
                }
            }
        }
        static void Main(string[] args)
        {
            Program obj = new Program();
        }
    }
}
现在的问题是如果节点的值存在差异,如何找到两个文件中不同的字符串部分......