Exemple #1
0
        static void Main(string[] args)
        {
            var sourceXml =
                File.ReadAllText(@"C:\Samples\XMLComparionApps\XMLComparionApps\41.xml");
            var targetXml =
                File.ReadAllText(@"C:\Samples\XMLComparionApps\XMLComparionApps\42.xml");

            //var sourceXml =
            //    File.ReadAllText(@"C:\Samples\XMLComparionApps\XMLComparionApps\782100_B__Chassi_20190307_194830_915.xml");
            //var targetXml =
            //    File.ReadAllText(@"C:\Samples\XMLComparionApps\XMLComparionApps\782100_B__Chassi_20190318_195515_659.xml");

            var diffOptions = new XmlDiffOptions
            {
                IgnoreAttributeOrder = false,
                TwoWayMatch          = true,
                IgnoreChildOrder     = true,
                IgnoreCase           = true,
                IgnorePrefix         = false
            };

            var outputMatch = new List <ResultDto>();

            CompareXmls(sourceXml, targetXml, diffOptions, out outputMatch);
            ProcessOutput(outputMatch);
            Console.ReadLine();
        }
Exemple #2
0
        /// <summary>
        /// Compare a ubl document class instance with a xml file on disk.
        /// </summary>
        public static bool IsCopyEqual <T>(string filename, T ublLarsenDoc) where T : UblLarsen.Ubl2.UblBaseDocumentType
        {
            bool areEqual = true;

            using (XmlReader fileReader = CreateReaderForFile(filename))
                using (XmlReader docReader = CreateReaderForDoc(ublLarsenDoc))
                {
                    XmlDiffOptions options = XmlDiffOptions.IgnoreComments | XmlDiffOptions.IgnoreWhitespace | XmlDiffOptions.IgnoreNamespaces | XmlDiffOptions.IgnorePI | XmlDiffOptions.IgnoreXmlDecl;
                    XmlDiff        xmlDiff = new XmlDiff(options);

                    using (MemoryStream diffgramStream = new MemoryStream())
                    {
                        string diff = "";
                        using (XmlTextWriter diffgramWriter = new XmlTextWriter(new StreamWriter(diffgramStream)))
                        {
                            areEqual = xmlDiff.Compare(fileReader, docReader, diffgramWriter);
                            if (!areEqual)
                            {
                                diffgramStream.Position = 0;
                                using (XmlTextReader tr = new XmlTextReader(diffgramStream))
                                {
                                    XDocument xdoc = XDocument.Load(tr);
                                    diff = xdoc.ToString();
                                    Console.WriteLine(diff);
                                }
                            }
                        }
                    }
                }
            return(areEqual);
        }
Exemple #3
0
        public void TestXmlDiff()
        {
            XmlDiff        diff    = new XmlDiff(TestResources.HAAR01000, TestResources.HAAR01001, "HAAR01000", "HAAR01001");
            XmlDiffOptions options = new XmlDiffOptions();

            options.IgnoreAttributeOrder   = true;
            options.IgnoreAttributes       = false;
            options.MaxAttributesToDisplay = 3;
            diff.CompareDocuments(options);
            Assert.AreEqual(diff.DiffNodeList.Count, 0);
            XmlDocument xdoc = new XmlDocument();

            xdoc.LoadXml(TestResources.HAAR01001);
            XmlNode node = xdoc.SelectSingleNode("//Product");

            node.Attributes["EffDate"].Value = "01/01/3000";
            diff = new XmlDiff(TestResources.HAAR01000, xdoc.InnerXml, "HAAR01000", "HAAR01001");
            diff.CompareDocuments(options);
            Assert.AreEqual(diff.DiffNodeList.Count, 2);
            Assert.IsTrue(diff.DiffNodeList[1].Description.Contains("EffDate"));
            xdoc.LoadXml(TestResources.HAAR01001);
            node = xdoc.SelectSingleNode("//Company");
            node.Attributes["CompanyID"].Value = "1000";
            diff = new XmlDiff(TestResources.HAAR01000, xdoc.InnerXml);
            diff.CompareDocuments(options);
            Assert.AreEqual(diff.DiffNodeList.Count, 2);
            Assert.IsTrue(diff.DiffNodeList[1].Description.Contains("CompanyID"));
        }
Exemple #4
0
        public void TryUpdateElementTest()
        {
            XmlDocument actualXmlDoc = new XmlDocument();

            actualXmlDoc.LoadXml(TestResources.updatenodetest);
            XmlDocument expectedXmlDoc = new XmlDocument();

            expectedXmlDoc.LoadXml(TestResources.updatenodeexpected);

            XmlNode insNode = actualXmlDoc.SelectSingleNode("ACORD/InsuranceSvcRq/PersAutoPolicyQuoteInqRq/PersAutoLineBusiness/PersDriver[@id = 'D1']");

            Assert.IsTrue(insNode.TryUpdateElement("DriverInfo/DriversLicense", "StateProvCd", "IT"));

            Assert.IsFalse(insNode.TryUpdateElement("DriverInfo/DriversLicense", "LicenseTypeCd", "Permit"));

            Assert.IsTrue(actualXmlDoc.TryUpdateElement("ACORD/InsuranceSvcRq/PersAutoPolicyQuoteInqRq/PersAutoLineBusiness/PersDriver[@id = 'D1']/DriverInfo/DriversLicense", "CountryCd", "CA", true));

            XmlDiff        diff    = new XmlDiff(actualXmlDoc.InnerXml, expectedXmlDoc.InnerXml);
            XmlDiffOptions options = new XmlDiffOptions();

            options.TwoWayMatch = true;
            Assert.IsTrue(diff.CompareDocuments(options));

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(TestResources.alliedreqxml);
            var node = xmlDoc.SelectSingleNode("//HomeLineBusiness/Dwell/Coverage[CoverageCd=\"DWELL\"]/Limit");

            Assert.IsTrue(node.TryUpdateElement("FormatInteger", "150000"));
            Assert.AreEqual("150000", xmlDoc.XPathSelectSingle("//HomeLineBusiness/Dwell/Coverage[CoverageCd='DWELL']/Limit/FormatInteger").GetValue());
        }
Exemple #5
0
        public void XmlMatchFormat()
        {
            string originalXML;
            string controlXML;

            var xml = GetType().Module.Assembly.GetManifestResourceStream("Carrousel1.Test.Resources.XML.Images.xml");

            using (StreamReader reader = new StreamReader(xml))
            {
                originalXML = reader.ReadToEnd();
            }

            var xmlControl = GetType().Module.Assembly.GetManifestResourceStream("Carrousel1.Test.Resources.XML.ImageControl.xml");

            using (StreamReader reader = new StreamReader(xmlControl))
            {
                controlXML = reader.ReadToEnd();
            }

            XmlDiff diff = new XmlDiff(controlXML, originalXML);

            XmlDiffOptions options = new XmlDiffOptions();

            var result = diff.CompareDocuments(options);

            Assert.IsTrue(diff.DiffNodeList.Count == 0);
        }
Exemple #6
0
        private void SetDiffOptions()
        {
            //Reset to None and refresh the options from the menuoptions
            //else eventually all options may get set and the menu changes will
            // not be reflected.
            diffOptions = XmlDiffOptions.None;


            //Read the options settings and OR the XmlDiffOptions enumeration.

            diffOptions = diffOptions | XmlDiffOptions.IgnorePI;
            diffOptions = diffOptions | XmlDiffOptions.IgnoreChildOrder;
            diffOptions = diffOptions | XmlDiffOptions.IgnoreComments;
            diffOptions = diffOptions | XmlDiffOptions.IgnoreDtd;
            diffOptions = diffOptions | XmlDiffOptions.IgnoreNamespaces;
            diffOptions = diffOptions | XmlDiffOptions.IgnorePrefixes;
            diffOptions = diffOptions | XmlDiffOptions.IgnoreWhitespace;
            diffOptions = diffOptions | XmlDiffOptions.IgnoreXmlDecl;

            compareFragments = true;

            //Default algorithm is Auto.
            diff.Algorithm = XmlDiffAlgorithm.Auto;

            // if (algFast.Checked)
            // diff.Algorithm = XmlDiffAlgorithm.Fast;

            //if (algPrecise.Checked)
            // diff.Algorithm = XmlDiffAlgorithm.Precise;

            diff.Options = diffOptions;
        }
Exemple #7
0
    public static SqlBoolean CompareXML_CLR(SqlXml xml1, SqlXml xml2, SqlBoolean ignoreOrder)
    {
        bool empty1 = xml1.IsNull || string.IsNullOrEmpty(xml1.Value);
        bool empty2 = xml2.IsNull || string.IsNullOrEmpty(xml2.Value);

        if (empty1 && empty2)
        {
            return(true);
        }

        if (empty1 || empty2)
        {
            return(false);
        }

        XmlDocument doc1 = GetXmlValue(xml1);
        XmlDocument doc2 = GetXmlValue(xml2);

        XmlDiffOptions option = XmlDiffOptions.IgnoreNamespaces | XmlDiffOptions.IgnorePrefixes |
                                (ignoreOrder ? XmlDiffOptions.IgnoreChildOrder : XmlDiffOptions.None);

        XmlDiff diff = new XmlDiff(option);

        return(diff.Compare(doc1, doc2));
    }
Exemple #8
0
        public static XmlDocument Porovnej(XmlDocument xdLevy, XmlDocument xdPravy)
        {
            XmlDocument xdd = null;

            try
            {
                XmlDiffOptions options        = XmlDiffOptions.None;
                MemoryStream   diffgram       = new MemoryStream();
                XmlTextWriter  diffgramWriter = new XmlTextWriter(new StreamWriter(diffgram));
                XmlDiff        xmlDiff        = new XmlDiff(options);
                //bool bIdentical = xmlDiff.Compare(@"V:\Temp\Evidence\1.xml", @"V:\Temp\Evidence\12.xml", false, diffgramWriter);
                bool bIdentical = xmlDiff.Compare(xdLevy.DocumentElement, xdPravy.DocumentElement, diffgramWriter);
                if (!bIdentical)
                {
                    diffgram.Seek(0, SeekOrigin.Begin);
                    xdd = new XmlDocument();
                    xdd.Load(new XmlTextReader(diffgram));
                    xdd.Save(@"V:\Temp\Evidence\diff.xml");
                }
            }
            catch
            {
                return(null);
            }

            /*
             * XmlDiff xd = new XmlDiff();
             * xd.Algorithm = XmlDiffAlgorithm.Precise;
             * xd.IgnoreWhitespace = true;
             * if (xd.Compare(@"V:\Temp\Evidence\1.xml", @"V:\Temp\Evidence\12.xml", true, xw))
             **/
            return(xdd);
        }
Exemple #9
0
        /// <summary>
        /// compares two xml data sources as xml strings
        /// </summary>
        /// <param name="querySource">the SQL query text for the source</param>
        /// <param name="queryTarget">the SQL query text for the target</param>
        /// <param name="connectionSource">The sql connection object for the source</param>
        /// <param name="connectionTarget">The sql connection object for the target</param>
        /// <param name="asTextFile"></param>
        /// <returns></returns>
        public static string CompareData(string querySource, string queryTarget, SqlConnection connectionSource, SqlConnection connectionTarget, bool asTextFile)
        {
            bool   isEqual    = false;
            string tempFile   = "TableDiffReport.html";
            string sourceName = querySource.Replace("select * from ", "").Split(' ')[0].Replace("\\", "_").Replace(":", "-") + ".xml";
            string targetName = queryTarget.Replace("select * from ", "").Split(' ')[0].Replace("\\", "_").Replace(":", "-") + ".xml";
            //output diff file.
            string         diffFile = sourceName.Replace(".xml", "") + "_DIFF_" + targetName;
            XmlDiffOptions xdo      = XmlDiffOptions.IgnoreWhitespace | XmlDiffOptions.IgnoreComments | XmlDiffOptions.IgnoreChildOrder | XmlDiffOptions.IgnoreNamespaces | XmlDiffOptions.IgnorePI;

            XmlDocument original = new XmlDocument();

            original.LoadXml(GetXMLData(querySource, connectionSource));
            original.Save(sourceName);
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(GetXMLData(queryTarget, connectionTarget));
            doc.Save(targetName);

            if (asTextFile)
            {
                XmlDiffView diffView = new XmlDiffView();
                diffView.DifferencesAsFormattedText(sourceName, targetName, diffFile.Replace(".xml", "") + ".txt", false, xdo);
                diffView = null;
                return(diffFile.Replace(".xml", "") + ".txt");
            }
            else
            {
                XmlTextWriter diffWriter = new XmlTextWriter(diffFile, Encoding.UTF8);
                diffWriter.Formatting = Formatting.Indented;
                using (diffWriter)
                {
                    XmlDiff diff = new XmlDiff();
                    isEqual      = diff.Compare(original, doc, diffWriter);
                    diff.Options = xdo;
                }

                if (isEqual)
                {
                    //This means the files were identical for given options.
                    MessageBox.Show("Tables are identical", "Identical",
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return(string.Empty);
                }

                using (XmlReader diffGram = XmlReader.Create(diffFile))
                {
                    XmlDiffView diffView = new XmlDiffView();
                    diffView.Load(new XmlNodeReader(original), diffGram);
                    using (TextWriter htmlWriter = new StreamWriter(tempFile))
                    {
                        SideBySideXmlNotepadHeader(sourceName, targetName, htmlWriter);
                        diffView.GetHtml(htmlWriter);
                    }
                    diffView = null;
                }
            }
            return(tempFile);
        }
 public Comparer(IDiffManager manager)
 {
     _results = new List<BaseDiffResultObject>();
     _diff = new XmlDiff();
     _diffOptions = new XmlDiffOptions();
     _tempFilePath = Path.GetTempFileName();
     Manager = manager;
 }
Exemple #11
0
 private void SetDiffOptions()
 {
     diffOptions  = XmlDiffOptions.None;
     diffOptions  = diffOptions | XmlDiffOptions.IgnoreChildOrder;
     diffOptions  = diffOptions | XmlDiffOptions.IgnoreComments;
     diffOptions  = diffOptions | XmlDiffOptions.IgnoreWhitespace;
     diff.Options = diffOptions;
 }
Exemple #12
0
        public static bool DocumentCompare(string document1,
                                           string document2,
                                           XmlDiffOptions diffOptions = XmlDiffOptions.IgnoreComments)
        {
            XmlDiff xmlDiff    = new XmlDiff(diffOptions);
            bool    bIdentical = xmlDiff.Compare(document1, document2, false);

            return(bIdentical);
        }
Exemple #13
0
        public static bool VerifySource(XmlNode node, ulong hashValue, XmlDiffOptions options)
        {
            if (node == null)
            {
                throw new ArgumentNullException(nameof(node));
            }
            var hash = new XmlHash().ComputeHash(node, options);

            return((long)hashValue == (long)hash);
        }
Exemple #14
0
        public void TestXmlDiffWithCompareFunction()
        {
            XmlDiffOptions options = new XmlDiffOptions()
            {
                CompareFunction = DoubleCompare
            };
            XmlDiff diff = new XmlDiff(TestResources.exampleA_Function, TestResources.exampleB_Function);

            diff.CompareDocuments(options);
            Assert.AreEqual(diff.DiffNodeList.Count, 2);
        }
        public CoordinateSystemXmlReaderTest()
        {
            XmlDiffOptions ignoreMost = XmlDiffOptions.IgnoreChildOrder |
                                        XmlDiffOptions.IgnoreComments |
                                        XmlDiffOptions.IgnoreDtd |
                                        XmlDiffOptions.IgnorePI |
                                        XmlDiffOptions.IgnoreWhitespace |
                                        XmlDiffOptions.IgnoreXmlDecl;

            _xmlDiff = new XmlDiff(ignoreMost);
        }
Exemple #16
0
 internal ulong ComputeHash(XmlNode node, XmlDiffOptions options)
 {
     this._bIgnoreChildOrder = (options & XmlDiffOptions.IgnoreChildOrder) > XmlDiffOptions.None;
     this._bIgnoreComments   = (options & XmlDiffOptions.IgnoreComments) > XmlDiffOptions.None;
     this._bIgnorePI         = (options & XmlDiffOptions.IgnorePI) > XmlDiffOptions.None;
     this._bIgnoreWhitespace = (options & XmlDiffOptions.IgnoreWhitespace) > XmlDiffOptions.None;
     this._bIgnoreNamespaces = (options & XmlDiffOptions.IgnoreNamespaces) > XmlDiffOptions.None;
     this._bIgnorePrefixes   = (options & XmlDiffOptions.IgnorePrefixes) > XmlDiffOptions.None;
     this._bIgnoreXmlDecl    = (options & XmlDiffOptions.IgnoreXmlDecl) > XmlDiffOptions.None;
     this._bIgnoreDtd        = (options & XmlDiffOptions.IgnoreDtd) > XmlDiffOptions.None;
     return(this.ComputeHash(node));
 }
        private void PreprocessDiffgram(XmlDocument diffgramDoc)
        {
            // read xmldiff options
            XmlAttribute attr = (XmlAttribute)diffgramDoc.DocumentElement.Attributes.GetNamedItem("options");

            if (attr == null)
            {
                throw new Exception("Missing 'options' attribute in the diffgram.");
            }
            string         optionsAttr = attr.Value;
            XmlDiffOptions options     = XmlDiff.ParseOptions(optionsAttr);

            _bIgnoreChildOrder = (((int)options & (int)(XmlDiffOptions.IgnoreChildOrder)) > 0);
            _bIgnoreComments   = (((int)options & (int)(XmlDiffOptions.IgnoreComments)) > 0);
            _bIgnorePI         = (((int)options & (int)(XmlDiffOptions.IgnorePI)) > 0);
            _bIgnoreWhitespace = (((int)options & (int)(XmlDiffOptions.IgnoreWhitespace)) > 0);
            _bIgnoreNamespaces = (((int)options & (int)(XmlDiffOptions.IgnoreNamespaces)) > 0);
            _bIgnorePrefixes   = (((int)options & (int)(XmlDiffOptions.IgnorePrefixes)) > 0);
            _bIgnoreDtd        = (((int)options & (int)(XmlDiffOptions.IgnoreDtd)) > 0);

            if (_bIgnoreNamespaces)
            {
                _bIgnorePrefixes = true;
            }

            // read descriptors
            XmlNodeList children = diffgramDoc.DocumentElement.ChildNodes;
            IEnumerator e        = children.GetEnumerator();

            while (e.MoveNext())
            {
                XmlElement desc = e.Current as XmlElement;
                if (desc != null && desc.LocalName == "descriptor")
                {
                    int opid = int.Parse(desc.GetAttribute("opid"));
                    OperationDescriptor.Type type;
                    switch (desc.GetAttribute("type"))
                    {
                    case "move":             type = OperationDescriptor.Type.Move; break;

                    case "prefix change":    type = OperationDescriptor.Type.PrefixChange; break;

                    case "namespace change": type = OperationDescriptor.Type.NamespaceChange; break;

                    default:
                        throw new Exception("Invalid descriptor type.");
                    }
                    OperationDescriptor od = new OperationDescriptor(opid, type);
                    _descriptors[opid] = od;
                }
            }
        }
    internal ulong ComputeHash( XmlNode node, XmlDiffOptions options )
    {
        _bIgnoreChildOrder = ( ( (int)options & (int)(XmlDiffOptions.IgnoreChildOrder) ) > 0 ) ;
        _bIgnoreComments   = ( ( (int)options & (int)(XmlDiffOptions.IgnoreComments)   ) > 0 ) ;
        _bIgnorePI         = ( ( (int)options & (int)(XmlDiffOptions.IgnorePI)         ) > 0 ) ;
        _bIgnoreWhitespace = ( ( (int)options & (int)(XmlDiffOptions.IgnoreWhitespace) ) > 0 ) ;
        _bIgnoreNamespaces = ( ( (int)options & (int)(XmlDiffOptions.IgnoreNamespaces) ) > 0 ) ;
        _bIgnorePrefixes   = ( ( (int)options & (int)(XmlDiffOptions.IgnorePrefixes)   ) > 0 ) ;
        _bIgnoreXmlDecl    = ( ( (int)options & (int)(XmlDiffOptions.IgnoreXmlDecl)    ) > 0 ) ;
        _bIgnoreDtd        = ( ( (int)options & (int)(XmlDiffOptions.IgnoreDtd)        ) > 0 ) ;

        return ComputeHash( node );
    }
Exemple #19
0
        internal ulong ComputeHash(XmlNode node, XmlDiffOptions options)
        {
            _bIgnoreChildOrder = (((int)options & (int)(XmlDiffOptions.IgnoreChildOrder)) > 0);
            _bIgnoreComments   = (((int)options & (int)(XmlDiffOptions.IgnoreComments)) > 0);
            _bIgnorePI         = (((int)options & (int)(XmlDiffOptions.IgnorePI)) > 0);
            _bIgnoreWhitespace = (((int)options & (int)(XmlDiffOptions.IgnoreWhitespace)) > 0);
            _bIgnoreNamespaces = (((int)options & (int)(XmlDiffOptions.IgnoreNamespaces)) > 0);
            _bIgnorePrefixes   = (((int)options & (int)(XmlDiffOptions.IgnorePrefixes)) > 0);
            _bIgnoreXmlDecl    = (((int)options & (int)(XmlDiffOptions.IgnoreXmlDecl)) > 0);
            _bIgnoreDtd        = (((int)options & (int)(XmlDiffOptions.IgnoreDtd)) > 0);

            return(ComputeHash(node));
        }
        /// <summary>
        /// Return the default XML difference options to use.
        /// </summary>
        /// <returns></returns>
        public static XmlDiffOptions DefaultDiffOptions()
        {
            var diffOptions = new XmlDiffOptions();
            diffOptions = diffOptions | XmlDiffOptions.IgnorePI;
            diffOptions = diffOptions | XmlDiffOptions.IgnoreChildOrder;
            diffOptions = diffOptions | XmlDiffOptions.IgnoreComments;
            diffOptions = diffOptions | XmlDiffOptions.IgnoreDtd;
            diffOptions = diffOptions | XmlDiffOptions.IgnoreNamespaces;
            diffOptions = diffOptions | XmlDiffOptions.IgnorePrefixes;
            diffOptions = diffOptions | XmlDiffOptions.IgnoreWhitespace;
            diffOptions = diffOptions | XmlDiffOptions.IgnoreXmlDecl;

            return diffOptions;
        }
Exemple #21
0
        /// <summary>
        /// Return the default XML difference options to use.
        /// </summary>
        /// <returns></returns>
        public static XmlDiffOptions DefaultDiffOptions()
        {
            var diffOptions = new XmlDiffOptions();

            diffOptions = diffOptions | XmlDiffOptions.IgnorePI;
            diffOptions = diffOptions | XmlDiffOptions.IgnoreChildOrder;
            diffOptions = diffOptions | XmlDiffOptions.IgnoreComments;
            diffOptions = diffOptions | XmlDiffOptions.IgnoreDtd;
            diffOptions = diffOptions | XmlDiffOptions.IgnoreNamespaces;
            diffOptions = diffOptions | XmlDiffOptions.IgnorePrefixes;
            diffOptions = diffOptions | XmlDiffOptions.IgnoreWhitespace;
            diffOptions = diffOptions | XmlDiffOptions.IgnoreXmlDecl;

            return(diffOptions);
        }
Exemple #22
0
        internal static XmlDiffOptions Set()
        {
            XmlDiffOptions result = 0;

            if (None)
            {
                result = XmlDiffOptions.None;
            }
            else
            {
                if (IgnoreChildOrder)
                {
                    result |= XmlDiffOptions.IgnoreChildOrder;
                }
                if (IgnoreComments)
                {
                    result |= XmlDiffOptions.IgnoreComments;
                }
                if (IgnoreDtd)
                {
                    result |= XmlDiffOptions.IgnoreDtd;
                }
                if (IgnoreNamespaces)
                {
                    result |= XmlDiffOptions.IgnoreNamespaces;
                }
                if (IgnorePI)
                {
                    result |= XmlDiffOptions.IgnorePI;
                }
                if (IgnorePrefixes)
                {
                    result |= XmlDiffOptions.IgnorePrefixes;
                }
                if (IgnoreWhitespace)
                {
                    result |= XmlDiffOptions.IgnoreWhitespace;
                }
                if (IgnoreXmlDecl)
                {
                    result |= XmlDiffOptions.IgnoreXmlDecl;
                }
            }
            return(result);
        }
        public BaseDiffResultObjectList DoCompare(string originalDocumentPath, string changedDocumentPath, string outputFilePath, XmlDiffOptions options)
        {
            Assert.StringIsNullOrEmpty(originalDocumentPath, "First File path is empty");
            Assert.StringIsNullOrEmpty(changedDocumentPath, "Second File path is empty");
            Assert.StringIsNullOrEmpty(outputFilePath, "Output File Path is empty");

            XmlTextReader originalDocumentReader = new XmlTextReader(new StreamReader(originalDocumentPath));
            XmlTextReader changedDocumentReader = new XmlTextReader(new StreamReader(changedDocumentPath));

            XmlDocument originalDocument = new XmlDocument();

            originalDocument.Load(originalDocumentReader);
            originalDocumentReader.Close();

            XmlDocument changedDocument = new XmlDocument();
            changedDocument.Load(changedDocumentReader);
            return DoCompare(originalDocument.DocumentElement, changedDocument.DocumentElement, outputFilePath, options);
        }
Exemple #24
0
        private static void CompareXmls(string sourceXml, string targetXml, XmlDiffOptions diffOptions, out List <ResultDto> outputSourceToTarget)
        {
            try
            {
                outputSourceToTarget = null;
                var diff1 = new XmlDiff(sourceXml, targetXml);

                diff1.CompareDocuments(diffOptions);

                if (diff1.DiffNodeList.Count > 0)
                {
                    Console.WriteLine(diff1.ToString());
                    var dataList = diff1.DiffNodeList.Select(z => z).OrderBy(z => z.DiffId).ToList();

                    var resultList = new List <ResultDto>();
                    foreach (var record in dataList)
                    {
                        MakeResult(record, resultList);
                    }

                    var resultsTobeDisplayed = resultList.Where(x => x.NodeType != "Node").ToList();

                    foreach (var record in resultsTobeDisplayed)
                    {
                        var initialDescription = "";
                        initialDescription = MakeDescription(record, initialDescription);
                        var completeDescription = new StringBuilder();
                        completeDescription.Append("DiffType:");
                        completeDescription.Append(initialDescription);
                        completeDescription.Append(record.DiffType);
                        completeDescription.Append(" ; Xpath : " + record.XPath + " ; " +
                                                   record.Description);
                        record.ResultantOutput = completeDescription.ToString();
                        //Console.WriteLine(completeDescription);
                    }

                    outputSourceToTarget = resultsTobeDisplayed;
                }
            }
            catch (Exception ex)
            {
                outputSourceToTarget = null;
            }
        }
Exemple #25
0
        public static bool DocumentCompare(string document1,
                                           string document2, out string diff,
                                           XmlDiffOptions diffOptions = XmlDiffOptions.IgnoreComments)
        {
            XmlDiff       xmlDiff = new XmlDiff(diffOptions);
            StringBuilder sb      = new StringBuilder();
            bool          bIdentical;

            using (StringWriter sw = new StringWriter(sb))
            {
                using (XmlTextWriter tw = new XmlTextWriter(sw))
                {
                    bIdentical = xmlDiff.Compare(document1, document2, false, tw);
                }
            }

            diff = sb.ToString();
            return(bIdentical);
        }
        public static XmlDiffOptions GetXmlDiffOptions(this Settings s)
        {
            XmlDiffOptions options = XmlDiffOptions.None;

            if ((bool)s["XmlDiffIgnoreChildOrder"])
            {
                options |= XmlDiffOptions.IgnoreChildOrder;
            }
            if ((bool)s["XmlDiffIgnoreComments"])
            {
                options |= XmlDiffOptions.IgnoreComments;
            }
            if ((bool)s["XmlDiffIgnorePI"])
            {
                options |= XmlDiffOptions.IgnorePI;
            }
            if ((bool)s["XmlDiffIgnoreWhitespace"])
            {
                options |= XmlDiffOptions.IgnoreWhitespace;
            }
            if ((bool)s["XmlDiffIgnoreNamespaces"])
            {
                options |= XmlDiffOptions.IgnoreNamespaces;
            }
            if ((bool)s["XmlDiffIgnorePrefixes"])
            {
                options |= XmlDiffOptions.IgnorePrefixes;
            }
            if ((bool)s["XmlDiffIgnoreXmlDecl"])
            {
                options |= XmlDiffOptions.IgnoreXmlDecl;
            }
            if ((bool)s["XmlDiffIgnoreDtd"])
            {
                options |= XmlDiffOptions.IgnoreDtd;
            }
            return(options);
        }
        public BaseDiffResultObjectList DoCompare(XmlNode originalDocument, XmlNode changedDocument, string outputFilePath, XmlDiffOptions options)
        {
            Assert.StringIsNullOrEmpty(outputFilePath, "Output File Path is empty");
            BaseDiffResultObjectList results = new BaseDiffResultObjectList();
            StreamWriter stream = new StreamWriter(outputFilePath, false);
            XmlTextWriter tw = new XmlTextWriter(stream);

            tw.Formatting = Formatting.Indented;
            SetDiffOptions(options);
            bool isEqual = false;

            try
            {
                isEqual = _diff.Compare(originalDocument, changedDocument, tw);
            }
            finally
            {
                tw.Close();
                stream.Close();
            }

            if (isEqual)
            {

                return results;
            }

            XmlTextReader diffGram = new XmlTextReader(outputFilePath);
            XmlDocument diffgramDoc = new XmlDocument();
            diffgramDoc.Load(diffGram);
            Manager.ApplyDiff(diffgramDoc.DocumentElement.FirstChild, originalDocument, ref results);
            return results;
        }
Exemple #28
0
        /// <summary>
        /// Compare resopnse from server with ethalon
        /// </summary>
        /// <param name="responseFile">Ethalon response file</param>
        /// <param name="responseFileReal">Real response file</param>
        /// <param name="resultMessage">Result mesage</param>
        /// <param name="pathToCompareFile">Path to file with comparation</param>
        /// <returns>Return true if file identical and false in other case</returns>
        private bool CompareResponse(string responseFile, string responseFileReal, out string resultMessage, ref string pathToCompareFile)
        {
            bool           result      = false;
            string         diffFile    = null;
            XmlDiff        diff        = new XmlDiff();
            XmlTextReader  orig        = null;
            XmlDiffOptions diffOptions = new XmlDiffOptions();
            StreamWriter   sw1         = null;
            XmlTextReader  diffGram    = null;

            //output diff file.
            diffFile = Path.GetDirectoryName(responseFileReal) + "\\vxd.out";
            XmlTextWriter tw = new XmlTextWriter(new StreamWriter(diffFile));

            tw.Formatting = Formatting.Indented;

            //This method sets the diff.Options property.
            diffOptions  = XmlDiffOptions.None;
            diff.Options = diffOptions;

            bool isEqual = false;

            //Now compare the two files.
            try
            {
                isEqual = diff.Compare(responseFile, responseFileReal, false, tw);
            }
            catch (XmlException ex)
            {
                pathToCompareFile = "";
                resultMessage     = ex.Message;
                result            = false;
                return(result);
            }
            finally
            {
                tw.Close();
            }

            if (isEqual)
            {
                //This means the files were identical for given options.
                result            = true;
                pathToCompareFile = "";
                resultMessage     = "Files are equal.";
                return(result); //dont need to show the differences.
            }

            //Files were not equal, so construct XmlDiffView.
            XmlDiffView dv = new XmlDiffView();

            result        = false;
            resultMessage = "Files are not equal.";

            try
            {
                //Load the original file again and the diff file.
                orig     = new XmlTextReader(responseFile);
                diffGram = new XmlTextReader(diffFile);
                dv.Load(orig,
                        diffGram);


                //Wrap the HTML file with necessary html and
                //body tags and prepare it before passing it to the GetHtml method.

                sw1 = new StreamWriter(pathToCompareFile);


                sw1.Write("<html><body><table width='100%'>");
                //Write Legend.
                sw1.Write("<tr><td colspan='2' align='center'><b>Legend:</b> <font style='background-color: yellow'" +
                          " color='black'>added</font>&nbsp;&nbsp;<font style='background-color: red'" +
                          " color='black'>removed</font>&nbsp;&nbsp;<font style='background-color: " +
                          "lightgreen' color='black'>changed</font>&nbsp;&nbsp;" +
                          "<font style='background-color: red' color='blue'>moved from</font>" +
                          "&nbsp;&nbsp;<font style='background-color: yellow' color='blue'>moved to" +
                          "</font>&nbsp;&nbsp;<font style='background-color: white' color='#AAAAAA'>" +
                          "ignored</font></td></tr>");


                sw1.Write("<tr><td><b> File Name : ");
                sw1.Write(responseFile);
                sw1.Write("</b></td><td><b> File Name : ");
                sw1.Write(responseFileReal);
                sw1.Write("</b></td></tr>");

                //This gets the differences but just has the
                //rows and columns of an HTML table
                dv.GetHtml(sw1);

                //Finish wrapping up the generated HTML and complete the file.
                sw1.Write("</table></body></html>");
            }
            catch (Exception ex)
            {
                resultMessage = ex.Message;
                result        = false;
                return(result); //dont need to show the differences.
            }
            finally
            {
                //HouseKeeping...close everything we dont want to lock.
                if (sw1 != null)
                {
                    sw1.Close();
                }
                ;
                dv = null;
                if (orig != null)
                {
                    orig.Close();
                }
                ;
                if (diffGram != null)
                {
                    diffGram.Close();
                }
                ;
            }

            resultMessage = "File are not equal.";
            return(result);
        }
Exemple #29
0
        static void Main(string[] args)
        {
            bool             bFragment = false;
            bool             bNodes    = false;
            XmlDiffAlgorithm algorithm = XmlDiffAlgorithm.Auto;

            try
            {
                if (args.Length < 3)
                {
                    WriteUsage();
                    return;
                }

                XmlDiffOptions options = XmlDiffOptions.None;

                // process options
                int    curArgsIndex  = 0;
                string optionsString = string.Empty;
                while (args[curArgsIndex][0] == '/')
                {
                    if (args[curArgsIndex].Length != 2)
                    {
                        System.Console.Write("Invalid option: " + args[curArgsIndex] + "\n");
                        return;
                    }

                    switch (args[curArgsIndex][1])
                    {
                    case 'o':
                        options |= XmlDiffOptions.IgnoreChildOrder;
                        break;

                    case 'c':
                        options |= XmlDiffOptions.IgnoreComments;
                        break;

                    case 'p':
                        options |= XmlDiffOptions.IgnorePI;
                        break;

                    case 'w':
                        options |= XmlDiffOptions.IgnoreWhitespace;
                        break;

                    case 'n':
                        options |= XmlDiffOptions.IgnoreNamespaces;
                        break;

                    case 'r':
                        options |= XmlDiffOptions.IgnorePrefixes;
                        break;

                    case 'x':
                        options |= XmlDiffOptions.IgnoreXmlDecl;
                        break;

                    case 'd':
                        options |= XmlDiffOptions.IgnoreDtd;
                        break;

                    case 'e':
                        bNodes = true;
                        break;

                    case 'f':
                        bFragment = true;
                        break;

                    case 't':
                        algorithm = XmlDiffAlgorithm.Fast;
                        break;

                    case 'z':
                        algorithm = XmlDiffAlgorithm.Precise;
                        break;

                    default:
                        System.Console.Write("Invalid option: " + args[curArgsIndex] + "\n");
                        return;
                    }
                    optionsString += args[curArgsIndex][1];
                    curArgsIndex++;

                    if (args.Length - curArgsIndex < 3)
                    {
                        WriteUsage();
                        return;
                    }
                }

                // extract names from command line
                string sourceXml = args[curArgsIndex];
                string targetXml = args[curArgsIndex + 1];
                string diffgram  = args[curArgsIndex + 2];
                bool   bVerify   = (args.Length - curArgsIndex == 4) && (args[curArgsIndex + 3] == "verify");

                // write legend
                string legend = sourceXml.Substring(sourceXml.LastIndexOf("\\") + 1) + " & " +
                                targetXml.Substring(targetXml.LastIndexOf("\\") + 1) + " -> " +
                                diffgram.Substring(diffgram.LastIndexOf("\\") + 1);
                if (optionsString != string.Empty)
                {
                    legend += " (" + optionsString + ")";
                }

                if (legend.Length < 60)
                {
                    legend += new String(' ', 60 - legend.Length);
                }
                else
                {
                    legend += "\n" + new String(' ', 60);
                }

                System.Console.Write(legend);

                // create diffgram writer
                XmlWriter DiffgramWriter = new XmlTextWriter(diffgram, new System.Text.UnicodeEncoding());

                // create XmlDiff object & set the options
                XmlDiff xmlDiff = new XmlDiff(options);
                xmlDiff.Algorithm = algorithm;

                // compare xml files
                bool bIdentical;
                if (bNodes)
                {
                    if (bFragment)
                    {
                        Console.Write("Cannot have option 'd' and 'f' together.");
                        return;
                    }

                    XmlDocument sourceDoc = new XmlDocument();
                    sourceDoc.Load(sourceXml);
                    XmlDocument targetDoc = new XmlDocument();
                    targetDoc.Load(targetXml);

                    bIdentical = xmlDiff.Compare(sourceDoc, targetDoc, DiffgramWriter);
                }
                else
                {
                    bIdentical = xmlDiff.Compare(sourceXml, targetXml, bFragment, DiffgramWriter);
                }

/*
 *             if ( bMeasurePerf ) {
 *              Type type = xmlDiff.GetType();
 *              MemberInfo[] mi = type.GetMember( "_xmlDiffPerf" );
 *              if ( mi != null && mi.Length > 0 ) {
 *                  XmlDiffPerf xmldiffPerf = (XmlDiffPerf)type.InvokeMember( "_xmlDiffPerf", BindingFlags.GetField, null, xmlDiff, new object[0]);
 *              }
 *          }
 */

                // write result
                if (bIdentical)
                {
                    System.Console.Write("identical");
                }
                else
                {
                    System.Console.Write("different");
                }

                DiffgramWriter.Close();

                // verify
                if (!bIdentical && bVerify)
                {
                    XmlNode sourceNode;
                    if (bFragment)
                    {
                        NameTable     nt = new NameTable();
                        XmlTextReader tr = new XmlTextReader(new FileStream(sourceXml, FileMode.Open, FileAccess.Read),
                                                             XmlNodeType.Element,
                                                             new XmlParserContext(nt, new XmlNamespaceManager(nt),
                                                                                  string.Empty, XmlSpace.Default));
                        XmlDocument         doc  = new XmlDocument();
                        XmlDocumentFragment frag = doc.CreateDocumentFragment();

                        XmlNode node;
                        while ((node = doc.ReadNode(tr)) != null)
                        {
                            if (node.NodeType != XmlNodeType.Whitespace)
                            {
                                frag.AppendChild(node);
                            }
                        }

                        sourceNode = frag;
                    }
                    else
                    {
                        // load source document
                        XmlDocument sourceDoc = new XmlDocument();
                        sourceDoc.XmlResolver = null;
                        sourceDoc.Load(sourceXml);
                        sourceNode = sourceDoc;
                    }

                    // patch it & save
                    new XmlPatch().Patch(ref sourceNode, new XmlTextReader(diffgram));
                    if (sourceNode.NodeType == XmlNodeType.Document)
                    {
                        ((XmlDocument)sourceNode).Save("_patched.xml");
                    }
                    else
                    {
                        XmlTextWriter tw = new XmlTextWriter("_patched.xml", Encoding.Unicode);
                        sourceNode.WriteTo(tw);
                        tw.Close();
                    }

                    XmlWriter diffgramWriter2 = new XmlTextWriter("_2ndDiff.xml", new System.Text.UnicodeEncoding());

                    // compare patched source document and target document
                    if (xmlDiff.Compare("_patched.xml", targetXml, bFragment, diffgramWriter2))
                    {
                        System.Console.Write(" - ok");
                    }
                    else
                    {
                        System.Console.Write(" - FAILED");
                    }

                    diffgramWriter2.Close();
                }
                System.Console.Write("\n");
            }
            catch (Exception e)
            {
                Console.Write("\n*** Error: " + e.Message + " (source: " + e.Source + ")\n");
            }

            if (System.Diagnostics.Debugger.IsAttached)
            {
                Console.Write("\nPress enter...\n");
                Console.Read();
            }
        }
 public BaseDiffResultObjectList DoCompare(string originalDocumentPath, string changedDocumentPath, XmlDiffOptions options)
 {
     return DoCompare(originalDocumentPath, changedDocumentPath, _tempFilePath, options);
 }
        /// <summary>
        /// Create WinDiff like static comparison in Html.
        /// </summary>
        /// <param name="sourceXmlFile">the baseline file</param>
        /// <param name="changedXmlFile">the actual (or target) file</param>
        /// <param name="resultHtmlViewFile">the html output file</param>
        /// <param name="fragment">the file is only an Xml fragment</param>
        /// <param name="appendToOutputFile">Append to existing output file</param>
        /// <param name="options">comparison filtering options</param>
        /// <returns>Differences were not found after filtering.</returns>
        public bool DifferencesSideBySideAsHtml(
            string sourceXmlFile,
            string changedXmlFile,
            string resultHtmlViewFile,
            bool fragment,
            bool appendToOutputFile,
            XmlDiffOptions options)
        {
            // Append to the specified output file.
            FileMode mode;
            if (appendToOutputFile)
            {
                mode = FileMode.Append;
            }
            else
            {
                mode = FileMode.Create;
            }
            this.outputData = new StreamWriter(
                new FileStream(
                resultHtmlViewFile,
                mode,
                FileAccess.Write));

            bool identicalData;
            try
            {
                identicalData = this.DifferencesSideBySideAsHtml(
                    sourceXmlFile,
                    changedXmlFile,
                    fragment,
                    options,
                    this.outputData);
            }
            finally
            {
                this.outputData.Close();
            }

            return identicalData;
        }
        /// <summary>
        /// Create WinDiff like static comparison in Html.
        /// </summary>
        /// <param name="sourceXmlFile">the baseline file</param>
        /// <param name="changedXmlFile">the actual (or target) file</param>
        /// <param name="fragment">the file is only an Xml fragment</param>
        /// <param name="options">comparison filtering options</param>
        /// <param name="reader">Readable output data stream</param>
        /// <returns>Differences were not found after filtering.</returns>
        public XmlDiffViewResults DifferencesSideBySideAsHtml(
            string sourceXmlFile,
            string changedXmlFile,
            bool fragment,
            XmlDiffOptions options)
        {
            MemoryStream data = new MemoryStream();
            try
            {
                this.outputData = new StreamWriter(
                    data,
                    System.Text.Encoding.Unicode);

                bool identicalData = this.DifferencesSideBySideAsHtml(
                    sourceXmlFile,
                    changedXmlFile,
                    fragment,
                    options,
                    this.outputData);

                // Move the data to the memory stream
                this.outputData.Flush();

                // Generate the final output using the returned values
                // from the differences comparison.
                this.finalOutput = new XmlDiffViewResults(data, identicalData);
            }
            finally
            {
                if (null != data)
                {
                    data.Close();
                }
            }            // return result of comparison
            return this.finalOutput;
        }
Exemple #33
0
        static void Main(string[] args)
        {
            try {
                int  curArgIndex = 0;
                bool bFragment   = false;

                // decode options
                XmlDiffOptions options       = XmlDiffOptions.None;
                string         optionsString = string.Empty;
                while (curArgIndex < args.Length &&
                       (args[curArgIndex][0] == '/' || args[curArgIndex][0] == '-'))
                {
                    if (args[curArgIndex].Length != 2)
                    {
                        System.Console.Write("Invalid option: " + args[curArgIndex] + "\n");
                        return;
                    }

                    switch (args[curArgIndex][1])
                    {
                    case '?':
                        WriteUsage();
                        return;

                    case 'o':
                        options |= XmlDiffOptions.IgnoreChildOrder;
                        break;

                    case 'c':
                        options |= XmlDiffOptions.IgnoreComments;
                        break;

                    case 'p':
                        options |= XmlDiffOptions.IgnorePI;
                        break;

                    case 'w':
                        options |= XmlDiffOptions.IgnoreWhitespace;
                        break;

                    case 'n':
                        options |= XmlDiffOptions.IgnoreNamespaces;
                        break;

                    case 'r':
                        options |= XmlDiffOptions.IgnorePrefixes;
                        break;

                    case 'x':
                        options |= XmlDiffOptions.IgnoreXmlDecl;
                        break;

                    case 'd':
                        options |= XmlDiffOptions.IgnoreDtd;
                        break;

                    case 'f':
                        bFragment = true;
                        break;

                    default:
                        System.Console.Write("Invalid option: " + args[curArgIndex] + "\n");
                        return;
                    }
                    optionsString += args[curArgIndex][1];
                    curArgIndex++;
                }

                if (args.Length - curArgIndex < 3)
                {
                    WriteUsage();
                    return;
                }

                bool includeIngnore = (args.Length - curArgIndex > 3);

                string sourceXmlFile      = args[curArgIndex];
                string changedXmlFile     = args[curArgIndex + 1];
                string resultHtmlViewFile = args[curArgIndex + 2];
                string diffgramFile       = args[curArgIndex + 3];
                string ignoreFile         = includeIngnore ? args[curArgIndex + 4] : null;

                MemoryStream  diffgram       = new MemoryStream();
                XmlTextWriter diffgramWriter = new XmlTextWriter(new StreamWriter(diffgram));

                var msg = "Comparing " + sourceXmlFile + " to " + changedXmlFile + " using ignore config " + ignoreFile;
                log.Info(msg);
                Console.WriteLine(msg);

                XmlDiff xmlDiff    = new XmlDiff(options);
                bool    bIdentical = true;
                try
                {
                    bIdentical = xmlDiff.Compare(sourceXmlFile, changedXmlFile, bFragment, diffgramWriter, ignoreFile);
                }
                catch (Exception e)
                {
                    log.Error(e.Message, e);
                    Console.WriteLine(e.Message);
                    return;
                }

                msg = "Files compared " + (bIdentical ? "identical." : "different.");
                log.Info(msg);
                Console.WriteLine(msg);

                msg = "Generating " + resultHtmlViewFile + " view file";
                log.Info(msg);
                Console.WriteLine(msg);

                TextWriter resultHtml = new StreamWriter(new FileStream(resultHtmlViewFile, FileMode.Create, FileAccess.Write));
                resultHtml.WriteLine("<html><head>");
                resultHtml.WriteLine("<style TYPE='text/css' MEDIA='screen'>");
                resultHtml.Write("<!-- td { font-family: Courier New; font-size:14; } " +
                                 "th { font-family: Arial; } " +
                                 "p { font-family: Arial; } -->");
                resultHtml.WriteLine("</style></head>");
                resultHtml.WriteLine("<body><h3 style='font-family:Arial'>XmlDiff view</h3><table border='0'><tr><td><table border='0'>");
                resultHtml.WriteLine("<tr><th>" + sourceXmlFile + "</th><th>" +
                                     changedXmlFile + "</th></tr>" +
                                     "<tr><td colspan=2><hr size=1></td></tr>");
                if (bIdentical)
                {
                    resultHtml.WriteLine("<tr><td colspan='2' align='middle'>Files are identical.</td></tr>");
                }
                else
                {
                    resultHtml.WriteLine("<tr><td colspan='2' align='middle'>Files are different.</td></tr>");
                }

                diffgram.Seek(0, SeekOrigin.Begin);
                Microsoft.XmlDiffPatch.XmlDiffView xmlDiffView = new Microsoft.XmlDiffPatch.XmlDiffView();
                XmlTextReader sourceReader;
                if (bFragment)
                {
                    NameTable nt = new NameTable();
                    sourceReader = new XmlTextReader(new FileStream(sourceXmlFile, FileMode.Open, FileAccess.Read),
                                                     XmlNodeType.Element,
                                                     new XmlParserContext(nt, new XmlNamespaceManager(nt),
                                                                          string.Empty, XmlSpace.Default));
                }
                else
                {
                    sourceReader = new XmlTextReader(sourceXmlFile);
                }

                sourceReader.XmlResolver = null;
                xmlDiffView.Load(sourceReader, new XmlTextReader(diffgram));

                xmlDiffView.GetHtml(resultHtml);

                resultHtml.WriteLine("</table></table></body></html>");
                resultHtml.Close();

                msg = resultHtmlViewFile + " saved successfully.";
                log.Info(msg);
                Console.WriteLine(msg);

                msg = "saving diffgram file";
                log.Info(msg);
                Console.WriteLine(msg);

                using (FileStream file = new FileStream(diffgramFile, FileMode.Create, FileAccess.Write))
                {
                    diffgram.WriteTo(file);
                }

                msg = "diffgram file saved to " + diffgramFile;
                log.Info(msg);
                Console.WriteLine(msg);
            }
            catch (Exception e) {
                log.Error(e.Message, e);
                Console.WriteLine("Error: " + e.Message);
            }

            if (System.Diagnostics.Debugger.IsAttached)
            {
                Console.Write("\nPress enter...\n");
                Console.Read();
            }
        }
        /// <summary>
        /// Create WinDiff like static comparison in Html.
        /// </summary>
        /// <param name="sourceXmlFile">the baseline file</param>
        /// <param name="changedXmlFile">the actual (or target) file</param>
        /// <param name="resultHtmlViewFile">the html output file</param>
        /// <param name="fragment">the file is only an Xml fragment</param>
        /// <param name="options">comparison filtering options</param>
        /// <returns>Differences were not found after filtering.</returns>
        public bool DifferencesSideBySideAsHtml(
            string sourceXmlFile,
            string changedXmlFile,
            string resultHtmlViewFile,
            bool fragment,
            XmlDiffOptions options)
        {
            bool identicalData = this.DifferencesSideBySideAsHtml(
                sourceXmlFile,
                changedXmlFile,
                resultHtmlViewFile,
                fragment,
                true,
                options);

            return identicalData;
        }
Exemple #35
0
        static void Main(string[] args)
        {
            XmlDiffOptions xDiffOptions = new XmlDiffOptions();
            string         fromFile     = "C:\\Users\\rmiao\\Desktop\\configSample.xml";
            string         toFile       = fromFile;
            XmlDiff        xdiff;

            try
            {
                xdiff = new XmlDiff(File.ReadAllText(fromFile), File.ReadAllText(toFile));
                xdiff.CompareDocuments(xDiffOptions);
                Console.WriteLine(xdiff.ToString());
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
                return;
            }

            /*
             * string fromFile = string.Empty;
             * string toFile = string.Empty;
             * string outFile = string.Empty;
             * bool toCsv = false;
             *
             * var options = new GetOpt("XmlDiff: Tool for finding the difference between two Xml files.",
             * new[]
             * {
             * new CommandLineOption('o', "outfile", "Output file to write to. Files with csv extension open in Excel.",
             *  ParameterType.String, o => outFile = (string)o),
             * new CommandLineOption('\0', "csv", "Creates a diff csv file and opens in Excel. If no outfile is specified writes output to xmldiff.csv. Default=False",
             *  ParameterType.None, none => toCsv = true),
             * new CommandLineOption('m', "nomatch", "Don't match text node value types (i.e. 0.00 != 0). Default=False",
             *  ParameterType.None, none => xDiffOptions.MatchValueTypes = false),
             * new CommandLineOption('\0', "ignoretypes", "If -m or --nomatch is NOT chosen, then this chooses which match types to ignore. " +
             *                      "Possible values are (string, integer, double, datetime). Multiple values may be separated by '|'", ParameterType.String,
             *                      (types) =>
             *                        {
             *                          string[] values = ((string)types).Split('|');
             *                          foreach (string value in values)
             *                          {
             *                            switch (value.ToLower().Trim())
             *                            {
             *                              case "string":
             *                                xDiffOptions.IgnoreTextTypes.Add(XmlDiffOptions.IgnoreTextNodeOptions.XmlString);
             *                                break;
             *                              case "integer":
             *                                xDiffOptions.IgnoreTextTypes.Add(XmlDiffOptions.IgnoreTextNodeOptions.XmlInteger);
             *                                break;
             *                              case "double":
             *                                xDiffOptions.IgnoreTextTypes.Add(XmlDiffOptions.IgnoreTextNodeOptions.XmlDouble);
             *                                break;
             *                              case "datetime":
             *                                xDiffOptions.IgnoreTextTypes.Add(XmlDiffOptions.IgnoreTextNodeOptions.XmlDateTime);
             *                                break;
             *                              default:
             *                                throw new CommandLineException("Error parsing enumerated values.", "ignoretypes");
             *                            }
             *                          }
             *                        }),
             * new CommandLineOption('d', "nodetail", "Will not display details of matching nodes. Default=False", ParameterType.None, none => xDiffOptions.MatchDescendants = false),
             * new CommandLineOption('c', "case", "Case Sensitive. Default=False", ParameterType.None, none => xDiffOptions.IgnoreCase = false),
             * new CommandLineOption('\0', "2way", "Does a comparison in both directions. Default=False", ParameterType.None, none => xDiffOptions.TwoWayMatch = true),
             * new CommandLineOption("Required. FromFile", ParameterType.String, file => fromFile = (string)file),
             * new CommandLineOption("Required. ToFile", ParameterType.String, file => toFile = (string)file)
             * });
             *
             * try
             * {
             * options.ParseOptions(args);
             * }
             * catch (CommandLineException ex)
             * {
             * Console.WriteLine("Error: {0}", ex.Message);
             * return;
             * }
             *
             * StreamWriter sw;
             * XmlDiff xdiff;
             * try
             * {
             * xdiff = new XmlDiff(File.ReadAllText(fromFile), File.ReadAllText(toFile));
             * xdiff.CompareDocuments(xDiffOptions);
             * }
             * catch (Exception ex)
             * {
             * Console.WriteLine("Error: {0}", ex.Message);
             * return;
             * }
             *
             * if (toCsv)
             * {
             * try
             * {
             * string file;
             * if (!string.IsNullOrEmpty(outFile))
             *  file = outFile;
             * else
             *  file = "xmldiff.csv";
             * sw = new StreamWriter(file);
             * sw.Write((toCsv) ? xdiff.ToCSVString() : xdiff.ToJsonString());
             * sw.Close();
             * Process.Start(file);
             * }
             * catch (IOException ex)
             * {
             * Console.WriteLine("Error: {0}", ex.Message);
             * return;
             * }
             * }
             * else
             * {
             * if (string.IsNullOrEmpty(outFile))
             * Console.WriteLine(xdiff.ToJsonString());
             * else
             * {
             * try
             * {
             *  sw = new StreamWriter(outFile);
             *  sw.WriteLine(xdiff.ToJsonString());
             *  sw.Close();
             * }
             * catch (IOException ex)
             * {
             *  Console.WriteLine("Error: {0}", ex.Message);
             *  return;
             * }
             * }
             * }
             */
        }
 public BaseDiffResultObjectList DoCompare(XmlDocument originalDocument, XmlDocument changedDocument, string outputFilePath, XmlDiffOptions options)
 {
     return DoCompare(originalDocument.DocumentElement, changedDocument.DocumentElement, outputFilePath, options);
 }
 public BaseDiffResultObjectList DoCompare(XmlDocument originalDocument, XmlDocument changedDocument, XmlDiffOptions options)
 {
     return DoCompare(originalDocument.DocumentElement, changedDocument.DocumentElement, this._tempFilePath, options);
 }
Exemple #38
0
 /// <include file='doc\XmlDiff.uex' path='docs/doc[@for="XmlDiff.XmlDiff2"]/*' />
 /// <summary>
 ///    Constructs XmlDiff object with the given options. The values of XmlDiffOptions
 ///    may be combined using the operator '|'.
 /// </summary>
 public XmlDiff( XmlDiffOptions options ) : this()
 {
     Options = options;
 }
Exemple #39
0
 public XmlDiff(XmlDiffOptions options)
     : this()
 {
     this.Options = options;
 }
 private void SetDiffOptions(XmlDiffOptions options)
 {
     _diffOptions = options;
 }
Exemple #41
0
        private void GenerateXmlDiffReport(string sourceXmlFile, string sourceXmlContent, string changedXmlFile, string changedXmlContent, string resultHtmlViewFile, XmlDiffOptions options)
        {
            MemoryStream  diffgram         = new MemoryStream();
            XmlTextWriter diffgramWriter   = new XmlTextWriter(new StreamWriter(diffgram));
            var           sourceXmlStream  = new MemoryStream(sourceXmlContent.ToByteArray());
            XmlReader     sourceXmlReader  = XmlReader.Create(new StreamReader(sourceXmlStream));
            XmlReader     changedXmlReader = XmlReader.Create(new StreamReader(new MemoryStream(changedXmlContent.ToByteArray())));

            logger.LogInfo("Comparing " + sourceXmlFile + " & " + changedXmlFile);
            XmlDiff xmlDiff    = new XmlDiff(options);
            bool    bIdentical = xmlDiff.Compare(sourceXmlReader, changedXmlReader, diffgramWriter);

            logger.LogInfo("Files compared " + (bIdentical ? "identical." : "different."));

            var        resultMS   = new MemoryStream();
            var        resultSW   = new StreamWriter(resultMS);
            TextWriter resultHtml = resultSW;

            //Wrapping
            resultHtml.Write("<html><style>td{ max-width:1000px; }</style><body><table>");

            diffgram.Seek(0, SeekOrigin.Begin);
            XmlDiffView xmlDiffView = new XmlDiffView();

            sourceXmlStream.Position = 0;
            XmlTextReader sourceReader = new XmlTextReader(sourceXmlStream);

            sourceReader.XmlResolver = null;
            xmlDiffView.Load(sourceReader, new XmlTextReader(diffgram));
            //This gets the differences but just has the
            //rows and columns of an HTML table
            xmlDiffView.SideBySideHtmlHeader(sourceXmlFile, changedXmlFile, bIdentical, resultHtml);
            xmlDiffView.GetHtml(resultHtml);
            xmlDiffView.GetHtml(resultHtml);

            resultHtml.WriteLine("</table></table></body></html>");
            using (var fs = new FileStream(resultHtmlViewFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                resultMS.WriteTo(fs);
            }
            resultSW.Close();
            resultMS.Close();
            resultHtml.Close();

            logger.LogInfo(resultHtmlViewFile + " saved successfully.");
        }
        /// <summary>
        /// Compare the xml data files
        /// </summary>
        /// <param name="sourceXmlFile">baseline file</param>
        /// <param name="changedXmlFile">actual file</param>
        /// <param name="fragment">xml data fragment</param>
        /// <param name="options">comparison options</param>
        /// <returns>data is identical</returns>
        private bool GenerateDiffGram(
            string sourceXmlFile,
            string changedXmlFile,
            bool fragment,
            XmlDiffOptions options)
        {
            // set class scope variables
            // MemoryStream diffgram
            bool identicalData;
            this.diffgram = new MemoryStream();
            XmlTextWriter diffgramWriter = new XmlTextWriter(
                new StreamWriter(this.diffgram));

            Trace.WriteLine("Comparing " + sourceXmlFile +
                " & " + changedXmlFile);
            XmlDiffOptions xmlDiffOptions = (XmlDiffOptions)options;
            XmlDiff xmlDiff = new XmlDiff(xmlDiffOptions);

            try
            {
                identicalData = xmlDiff.Compare(
                    sourceXmlFile,
                    changedXmlFile,
                    fragment,
                    diffgramWriter);
            }
            catch (XmlException format)
            {
                Trace.WriteLine(format.Message);
                throw;
            }
            Trace.WriteLine("Files compared " +
                (identicalData ? "identical." : "different."));

            return identicalData;
        }
        /// <summary>
        /// Determines if the data changed
        /// </summary>
        /// <param name="sourceXmlFile">baseline file</param>
        /// <param name="changedXmlFile">actual file</param>
        /// <param name="fragment">xml data fragment</param>
        /// <param name="options">Comparison options</param>
        /// <returns>data is identical</returns>
        private bool GetDifferencesAsFormattedText(
            string sourceXmlFile,
            string changedXmlFile,
            bool fragment,
            XmlDiffOptions options)
        {
            bool identicalData = this.MarkupBaselineWithChanges(
                sourceXmlFile,
                changedXmlFile,
                fragment,
                options);

            // only generate the output if there are differences.
            if (!identicalData)
            {
                // Populate the output
                this.GetText(sourceXmlFile, changedXmlFile);
            }
            return identicalData;
        }
Exemple #44
0
    /// <include file='doc\XmlDiff.uex' path='docs/doc[@for="XmlDiff.VerifySource"]/*' />
    /// <summary>
    ///    Given a diffgram, this method verifies whether the given document/node is the original
    ///    source document/node for the diffgram. 
    /// </summary>
    /// <param name="node">Document/node to be verified.</param>
    /// <param name="hashValue">Value of the 'srcDocHash' attribute of the 'xd:xmldiff' element in diffgram.
    /// This is the hash value of the original source document. The document/node is verified if it yields
    /// the same hash value.</param>
    /// <param name="options">XmlDiff options selected when the document/node was compared. The hash value 
    /// of the document/node depends on these options.</param>
    /// <returns>True if the given document is the original source document for the diffgram.</returns>
    static public bool VerifySource( XmlNode node, ulong hashValue, XmlDiffOptions options )
    {
        if ( node == null )
            throw new ArgumentNullException( "node" );

        ulong computedHashValue = new XmlHash().ComputeHash( node, options );
        return hashValue == computedHashValue;
    }
        /// <summary>
        /// Markup the baseline data with changes
        /// </summary>
        /// <param name="sourceXmlFile">baseline xml data</param>
        /// <param name="changedXmlFile">xml data to which to compare</param>
        /// <param name="fragment">xml data fragment</param>
        /// <param name="options">comparison options</param>
        /// <returns>data is identical</returns>
        private bool MarkupBaselineWithChanges(
            string sourceXmlFile,
            string changedXmlFile,
            bool fragment,
            XmlDiffOptions options)
        {
            // generate the diffgram
            bool identicalData = this.GenerateDiffGram(
                sourceXmlFile,
                changedXmlFile,
                fragment,
                options);

            this.MergeDiffgramAndBaseline(
                sourceXmlFile,
                fragment);

            return identicalData;
        }
 public BaseDiffResultObjectList DoCompare(XmlNode originalDocument, XmlNode changedDocument, XmlDiffOptions options)
 {
     return DoCompare(originalDocument, changedDocument, _tempFilePath, options);
 }
        /// <summary>
        /// Write the differences in the Xml data 
        /// to the output file as formatted xml-like text.
        /// </summary>
        /// <param name="sourceXmlFile">baseline file</param>
        /// <param name="changedXmlFile">actual file</param>
        /// <param name="outputTextPath">Output data file for the data in text form</param>
        /// <param name="appendToOutputFile">Append output to the file</param>
        /// <param name="fragment">This is an xml data frament</param>
        /// <param name="options">Comparison options</param>
        /// <returns>data is identical</returns>
        public bool DifferencesAsFormattedText(
            string sourceXmlFile,
            string changedXmlFile,
            string outputTextPath,
            bool appendToOutputFile,
            bool fragment,
            XmlDiffOptions options)
        {
            // Append to the specified output file.
            FileMode mode;
            if (appendToOutputFile)
            {
                mode = FileMode.Append;
            }
            else
            {
                mode = FileMode.Create;
            }
            this.outputData = new StreamWriter(
                new FileStream(
                outputTextPath,
                mode,
                FileAccess.Write));

            bool identicalData;
            identicalData = this.GetDifferencesAsFormattedText(
                sourceXmlFile,
                changedXmlFile,
                fragment,
                options);

            // close the output stream to release the file.
            this.outputData.Close();

            return identicalData;
        }
Exemple #48
0
        static void Main(string[] args)
        {
            bool             fragments = false;
            XmlDiffAlgorithm algorithm = XmlDiffAlgorithm.Auto;
            XmlDiffOptions   options   = XmlDiffOptions.None;

            // process options
            int curArgsIndex = 0;

            while (curArgsIndex < args.Length &&
                   (args[curArgsIndex][0] == '/' || args[curArgsIndex][0] == '-'))
            {
                if (args[curArgsIndex].Length != 2)
                {
                    Console.WriteLine("Invalid option: " + args[curArgsIndex]);
                    WriteUsage();
                    return;
                }

                switch (args[curArgsIndex][1])
                {
                case 'o':
                    options |= XmlDiffOptions.IgnoreChildOrder;
                    break;

                case 'c':
                    options |= XmlDiffOptions.IgnoreComments;
                    break;

                case 'p':
                    options |= XmlDiffOptions.IgnorePI;
                    break;

                case 'w':
                    options |= XmlDiffOptions.IgnoreWhitespace;
                    break;

                case 'n':
                    options |= XmlDiffOptions.IgnoreNamespaces;
                    break;

                case 'r':
                    options |= XmlDiffOptions.IgnorePrefixes;
                    break;

                case 'x':
                    options |= XmlDiffOptions.IgnoreXmlDecl;
                    break;

                case 'd':
                    options |= XmlDiffOptions.IgnoreDtd;
                    break;

                case 'f':
                    fragments = true;
                    break;

                case 't':
                    algorithm = XmlDiffAlgorithm.Fast;
                    break;

                case 'z':
                    algorithm = XmlDiffAlgorithm.Precise;
                    break;

                case '?':
                    WriteUsage();
                    return;

                default:
                    Console.Write("Invalid option: " + args[curArgsIndex] + "\n");
                    return;
                }
                curArgsIndex++;
            }

            if (args.Length < 2)
            {
                Console.WriteLine("Invalid arguments.");
                WriteUsage();
                return;
            }

            // extract names from command line
            string sourceXmlFileName  = args[curArgsIndex];
            string changedXmlFileName = args[curArgsIndex + 1];
            string diffgramFileName   = (curArgsIndex + 2 < args.Length) ? args[curArgsIndex + 2] : null;

            Console.WriteLine("Comparing " + sourceXmlFileName + " to " + changedXmlFileName);

            // create XmlTextWriter where the diffgram will be saved
            XmlWriter diffgramWriter = null;

            if (diffgramFileName != null)
            {
                diffgramWriter = new XmlTextWriter(diffgramFileName, Encoding.Unicode);
            }

            // create XmlDiff object & set the desired options and algorithm
            XmlDiff xmlDiff = new XmlDiff(options);

            xmlDiff.Algorithm = algorithm;

            // Compare the XML files
            bool bEqual = false;

            try {
                bEqual = xmlDiff.Compare(sourceXmlFileName, changedXmlFileName, fragments, diffgramWriter);
            }
            catch (Exception e) {
                WriteError(e.Message);
                return;
            }
            if (bEqual)
            {
                Console.WriteLine("Files are identical.");
            }
            else
            {
                Console.WriteLine("Files are different.");
            }
            if (diffgramWriter != null)
            {
                diffgramWriter.Close();
                Console.WriteLine("XDL diffgram has been saved to " + diffgramFileName + ".");
            }
        }
        /// <summary>
        /// Append the differences in the Xml data 
        /// to the output file as formatted xml-like text.
        /// </summary>
        /// <param name="sourceXmlFile">baseline file</param>
        /// <param name="changedXmlFile">actual file</param>
        /// <param name="outputTextPath">output file for the data in text form</param>
        /// <param name="fragment">This is an xml data frament</param>
        /// <param name="options">Comparison options</param>
        /// <returns>Differences were not found.</returns>
        public bool DifferencesAsFormattedText(
            string sourceXmlFile,
            string changedXmlFile,
            string outputTextPath,
            bool fragment,
            XmlDiffOptions options)
        {
            bool identicalData = this.DifferencesAsFormattedText(
                sourceXmlFile,
                changedXmlFile,
                outputTextPath,
                true,
                fragment,
                options);

            return identicalData;
        }
        public static bool ComparingFilesAreEqual(FileInfo expectedXmlFile, FileInfo actualXmlFile, XmlDiffOptions options)
        {
            bool bIdentical = false;
            var  xmlDiff    = new XmlDiff(options);

            // contains the xml string revealing the differences between the two files if they are not identical.
            var xmlDiffGram   = new StringBuilder();
            var xmlDiffWriter = new XmlTextWriter(new StringWriter(xmlDiffGram));

            try
            {
                var expectedMasterXmlTextReader = new XmlTextReader(expectedXmlFile.OpenText())
                {
                    DtdProcessing = DtdProcessing.Parse, XmlResolver = null
                };
                var actualOutputXmlTextReader = new XmlTextReader(actualXmlFile.OpenText())
                {
                    DtdProcessing = DtdProcessing.Parse, XmlResolver = null
                };

                bIdentical = xmlDiff.Compare(expectedMasterXmlTextReader, actualOutputXmlTextReader, xmlDiffWriter);

                //close readers.
                expectedMasterXmlTextReader.Close();
                actualOutputXmlTextReader.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error occured on comparing files: {e.Message}");
            }
            xmlDiffWriter.Close();

            if (!bIdentical)
            {
                var resultHtmlFile = Path.Combine(actualXmlFile.Directory.FullName, actualXmlFile.Name + ".html");
                WriteHtmlDiffViewFile(expectedXmlFile.FullName, actualXmlFile.FullName, false, xmlDiffGram.ToString(),
                                      resultHtmlFile);

                Console.WriteLine($"XMLDiff Result of \'{expectedXmlFile.Name}\' & \'{actualXmlFile.Name}\' was \'Different\', see \'{resultHtmlFile}\'.");
            }

            return(bIdentical);
        }
        /// <summary>
        /// Write the differences in the Xml data 
        /// as formatted xml-like text return in
        /// a memory based TextReader object.
        /// </summary>
        /// <param name="sourceXmlFile">baseline file</param>
        /// <param name="changedXmlFile">actual file</param>
        /// <param name="fragment">This is an xml data frament</param>
        /// <param name="options">Comparison options</param>
        /// <param name="reader">A reference to return readable 
        /// formatted xml-like text.</param>
        /// <returns>data is identical</returns>
        public XmlDiffViewResults DifferencesAsFormattedText(
            string sourceXmlFile,
            string changedXmlFile,
            bool fragment,
            XmlDiffOptions options)
        {
            MemoryStream data = new MemoryStream();
            this.outputData = new StreamWriter(
                data,
                System.Text.Encoding.Unicode);

            bool identicalData;
            identicalData = this.GetDifferencesAsFormattedText(
                sourceXmlFile,
                changedXmlFile,
                fragment,
                options);

            // Move the data to the memory stream
            this.outputData.Flush();

            this.finalOutput = new XmlDiffViewResults(data, identicalData);

            // return result of comparison
            return this.finalOutput;
        }
        /// <summary>
        /// Determines if the data changed
        /// </summary>
        /// <param name="sourceXmlFile">baseline file</param>
        /// <param name="changedXmlFile">actual file</param>
        /// <param name="fragment">xml data fragment</param>
        /// <param name="options">Comparison options</param>
        /// <param name="resultHtml">output data</param>
        /// <returns>data is identical</returns>
        private bool DifferencesSideBySideAsHtml(
            string sourceXmlFile,
            string changedXmlFile,
            bool fragment,
            XmlDiffOptions options,
            TextWriter resultHtml)
        {
            bool identicalData = this.MarkupBaselineWithChanges(
                sourceXmlFile,
                changedXmlFile,
                fragment,
                options);

                this.SideBySideHtmlHeader(
                    sourceXmlFile,
                    changedXmlFile,
                    identicalData,
                    resultHtml);

            this.GetHtml(resultHtml);

            this.SideBySideHtmlFooter(resultHtml);

            return identicalData;
        }
Exemple #53
0
        /// <summary>
        /// This method reads the diff options set on the 
        /// menu and configures the XmlDiffOptions object.
        /// </summary>
        private void SetDiffOptions()
        {
            //Reset to None and refresh the options from the menuoptions
            //else eventually all options may get set and the menu changes will
            // not be reflected.
            diffOptions = XmlDiffOptions.None;

            //Read the options settings and OR the XmlDiffOptions enumeration.
            if (ipiOpt.Checked)
                diffOptions = diffOptions | XmlDiffOptions.IgnorePI;

            if (icoOpt.Checked)
                diffOptions = diffOptions | XmlDiffOptions.IgnoreChildOrder;

            if (icOpt.Checked)
                diffOptions = diffOptions | XmlDiffOptions.IgnoreComments;

            if (idtdOpt.Checked)
                diffOptions = diffOptions | XmlDiffOptions.IgnoreDtd;

            if (inOpt.Checked)
                diffOptions = diffOptions | XmlDiffOptions.IgnoreNamespaces;

            if (ipOpt.Checked)
                diffOptions = diffOptions | XmlDiffOptions.IgnorePrefixes;

            if (iwsOpt.Checked)
                diffOptions = diffOptions | XmlDiffOptions.IgnoreWhitespace;

            if (ixdOpt.Checked)
                diffOptions = diffOptions | XmlDiffOptions.IgnoreXmlDecl;

            if (fOpt.Checked)
                compareFragments = true;

            //Default algorithm is Auto.
            diff.Algorithm = XmlDiffAlgorithm.Auto;

            if ( algFast.Checked )
                diff.Algorithm = XmlDiffAlgorithm.Fast;

            if ( algPrecise.Checked )
                diff.Algorithm = XmlDiffAlgorithm.Precise;

            diff.Options = diffOptions;
        }