// Constructor internal MinimalTreeDistanceAlgo( XmlDiff xmlDiff ) { Debug.Assert( OperationCost.Length - 1 == (int)XmlDiffOperation.Undefined, "Correct the OperationCost array so that it reflects the XmlDiffOperation enum." ); Debug.Assert( xmlDiff != null ); _xmlDiff = xmlDiff; }
internal static bool CompareXML(XDocument xmlDocument1, XDocument xmlDocument2) { XmlDiff diff = new XmlDiff(); diff.IgnoreChildOrder = true; diff.IgnoreXmlDecl = true; diff.IgnoreWhitespace = true; diff.IgnoreComments = true; diff.IgnorePI = true; diff.IgnoreDtd = true; var doc1 = new XmlDocument(); doc1.LoadXml(xmlDocument1.ToString()); var doc2 = new XmlDocument(); doc2.LoadXml(xmlDocument2.ToString()); bool result = diff.Compare(doc1, doc2); return result; }
public void TestSerialization() { MSBuildCodeMetricsReport report = MSBuildCodeMetricsReport.Create().CreateSummary().Report.CreateDetails().Report; report.Summary.AddMetric("VisualStudioMetrics", _cyclomaticComplexity).CreateRanges(). AddRange("> 10", 5). AddRange("<= 10 and > 5", 3). AddRange("<= 5", 1); report.Summary.AddMetric("VisualStudioMetrics", _linesOfCode).CreateRanges(). AddRange("> 100", 5). AddRange("<= 100 and > 50", 3). AddRange("<= 50", 1); report.Details.AddMetric("VisualStudioMetrics", _cyclomaticComplexity).CreateMeasures(). AddMeasure("Method1() : void", 100). AddMeasure("Method2() : void", 50); report.Details.AddMetric("VisualStudioMetrics", _linesOfCode).CreateMeasures(). AddMeasure("Method1() : void", 1000). AddMeasure("Method2() : void", 500); Stream ms = report.SerializeToMemoryStream(true); XmlDiff diff = new XmlDiff(); Assert.IsTrue(diff.Compare(_expectedReportStream, ms)); }
public Comparer(IDiffManager manager) { _results = new List<BaseDiffResultObject>(); _diff = new XmlDiff(); _diffOptions = new XmlDiffOptions(); _tempFilePath = Path.GetTempFileName(); Manager = manager; }
internal static void Equal(string file1, string file2) { var diffFile = @"diff.xml"; XmlTextWriter tw = new XmlTextWriter(new StreamWriter(diffFile)); tw.Formatting = Formatting.Indented; var diff = new XmlDiff(); diff.Options = XmlDiffOptions.IgnoreWhitespace | XmlDiffOptions.IgnoreComments | XmlDiffOptions.IgnoreXmlDecl; var result = diff.Compare(file1, file2, false, tw); tw.Close(); if (!result) { //Files were not equal, so construct XmlDiffView. XmlDiffView dv = new XmlDiffView(); //Load the original file again and the diff file. XmlTextReader orig = new XmlTextReader(file1); XmlTextReader diffGram = new XmlTextReader(diffFile); dv.Load(orig, diffGram); string tempFile = "test.htm"; StreamWriter sw1 = new StreamWriter(tempFile); //Wrapping sw1.Write("<html><body><table>"); sw1.Write("<tr><td><b>"); sw1.Write(file1); sw1.Write("</b></td><td><b>"); sw1.Write(file2); 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 by putting legend in the end just like the //online tool. sw1.Write("<tr><td><b>Legend:</b> <font style='background-color: yellow'" + " color='black'>added</font> <font style='background-color: red'" + "color='black'>removed</font> <font style='background-color: " + "lightgreen' color='black'>changed</font> " + "<font style='background-color: red' color='blue'>moved from</font>" + " <font style='background-color: yellow' color='blue'>moved to" + "</font> <font style='background-color: white' color='#AAAAAA'>" + "ignored</font></td></tr>"); sw1.Write("</table></body></html>"); //HouseKeeping...close everything we dont want to lock. sw1.Close(); orig.Close(); diffGram.Close(); Process.Start("test.htm"); } Assert.True(result); }
/// <summary> /// Create a default XML difference engine using the <see cref="DefaultDiffOptions" /> /// </summary> /// <returns></returns> public static XmlDiff DefaultDiffEngine() { var xmlDiff = new XmlDiff { Options = DefaultDiffOptions(), Algorithm = XmlDiffAlgorithm.Auto }; return xmlDiff; }
public CoordinateSystemXmlReaderTest() { XmlDiffOptions ignoreMost = XmlDiffOptions.IgnoreChildOrder | XmlDiffOptions.IgnoreComments | XmlDiffOptions.IgnoreDtd | XmlDiffOptions.IgnorePI | XmlDiffOptions.IgnoreWhitespace | XmlDiffOptions.IgnoreXmlDecl ; _xmlDiff = new XmlDiff(ignoreMost); }
// Constructor internal XmlHash( XmlDiff xmlDiff ) { // set flags _bIgnoreChildOrder = xmlDiff.IgnoreChildOrder; _bIgnoreComments = xmlDiff.IgnoreComments; _bIgnorePI = xmlDiff.IgnorePI; _bIgnoreWhitespace = xmlDiff.IgnoreWhitespace; _bIgnoreNamespaces = xmlDiff.IgnoreNamespaces; _bIgnorePrefixes = xmlDiff.IgnorePrefixes; _bIgnoreXmlDecl = xmlDiff.IgnoreXmlDecl; _bIgnoreDtd = xmlDiff.IgnoreDtd; }
private static XmlDiff GetDiffTool() { var diff = new Microsoft.XmlDiffPatch.XmlDiff(); diff.IgnoreWhitespace = true; diff.IgnoreComments = true; diff.IgnoreXmlDecl = true; diff.IgnoreDtd = true; //diff.IgnoreChildOrder = true; diff.IgnorePrefixes = true; return(diff); }
public XElement GenerateDiffGram(XElement element1, XElement element2) { using (var node1Reader = element1.CreateReader()) using (var node2Reader = element2.CreateReader()) { var result = new XDocument(); using (var writer = result.CreateWriter()) { var diff = new XmlDiff(XmlDiffOptions.IgnoreChildOrder | XmlDiffOptions.IgnoreWhitespace | XmlDiffOptions.IgnoreComments | XmlDiffOptions.IgnoreXmlDecl); diff.Compare(node1Reader, node2Reader, writer); writer.Flush(); writer.Close(); } return result.Root; } }
public static void DiffXmlStrict(string actual, string expected) { XmlDocument expectedDoc; XmlDocument actualDoc; try { expectedDoc = new XmlDocument(); expectedDoc.LoadXml(expected); } catch (XmlException e) { throw new Exception("Expected: " + e.Message + "\r\n" + expected); } try { actualDoc = new XmlDocument(); actualDoc.LoadXml(actual); } catch (XmlException e) { throw new Exception("Actual: " + e.Message + "\r\n" + actual); } using (var stringWriter = new StringWriter()) using (var writer = new XmlTextWriter(stringWriter)) { writer.Formatting = Formatting.Indented; var xmldiff = new XmlDiff(XmlDiffOptions.None //XmlDiffOptions.IgnoreChildOrder | | XmlDiffOptions.IgnoreNamespaces //XmlDiffOptions.IgnorePrefixes ); var identical = xmldiff.Compare(expectedDoc, actualDoc, writer); if (!identical) { var error = string.Format("Expected:\r\n{0}\r\n\r\n" + "Actual:\r\n{1}\r\n\r\nDiff:\r\n{2}", expected, actual, stringWriter.GetStringBuilder()); throw new Exception(error); } } }
public static bool CompareJson(string expected, string actual) { var expectedDoc = JsonConvert.DeserializeXmlNode(expected, "root"); var actualDoc = JsonConvert.DeserializeXmlNode(actual, "root"); var diff = new XmlDiff(XmlDiffOptions.IgnoreWhitespace | XmlDiffOptions.IgnoreChildOrder); using (var ms = new MemoryStream()) { var writer = new XmlTextWriter(ms, Encoding.UTF8); var result = diff.Compare(expectedDoc, actualDoc, writer); if (!result) { ms.Seek(0, SeekOrigin.Begin); Console.WriteLine(new StreamReader(ms).ReadToEnd()); } return result; } }
public void Serializable() { XmlDiff diff = new XmlDiff(); LayoutBox layoutBox = LayoutBox.LoadFromString(LayoutingResource.LayoutsDefault); String result = layoutBox.Serialize(); diff.IgnoreChildOrder = true; diff.IgnoreComments = true; diff.IgnoreDtd = true; diff.IgnoreNamespaces = true; diff.IgnorePI = true; diff.IgnorePrefixes = true; diff.IgnoreWhitespace = true; diff.IgnoreXmlDecl = true; StringWriter diffgramString = new StringWriter(); XmlTextWriter diffgramXml = new XmlTextWriter(diffgramString); bool diffBool = diff.Compare(new XmlTextReader(new StringReader(result)), new XmlTextReader(new StringReader(LayoutingResource.LayoutsDefault)), diffgramXml); //MessageBox.Show(diffgramString.ToString()); Assert.True(diffBool); }
/// <summary> /// Compares the two XML files and throws an error if they are different. /// </summary> public static void Compare(XmlDocument expected, XmlDocument actual) { XmlNamespaceManager ns = new XmlNamespaceManager(expected.NameTable); ns.AddNamespace("tst", "http://schemas.asidua.com/testing"); var diffReport = new StringBuilder(); // Remove the ignored nodes from both XML documents foreach (XmlAttribute ignored in expected.SelectNodes("//@tst:IGNORE[.='Content']", ns)) { string xpath = generateXPath(ignored.OwnerElement); // Remove the node's content from the expected results ignored.OwnerElement.InnerText = ""; ignored.OwnerElement.RemoveAttribute(ignored.Name); // Remove the node's content from the actual results var node = actual.SelectSingleNode(xpath); if (node != null) node.InnerText = ""; } XmlDiff comparer = new XmlDiff(); comparer.Options = XmlDiffOptions.IgnoreComments | XmlDiffOptions.IgnoreNamespaces | XmlDiffOptions.IgnorePrefixes | XmlDiffOptions.IgnoreWhitespace | XmlDiffOptions.IgnoreXmlDecl; var settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true, }; using (var writer = XmlWriter.Create(diffReport, settings)) { Assert.IsTrue( comparer.Compare(expected, actual, writer), "Expected Results:\n{0}\n\n" + "Actual Results:\n{1}\n\n" + "Difference Report:\n{2}", formatXml(expected), formatXml(actual), diffReport ); } }
private static void Main(string[] args) { var bFragments = false; var flag1 = false; var xmlDiffAlgorithm = XmlDiffAlgorithm.Auto; try { if (args.Length < 3) { TestXmlDiff.WriteUsage(); return; } var options = XmlDiffOptions.None; var index = 0; var empty = string.Empty; while (args[index][0] == '/') { if (args[index].Length != 2) { Console.Write("Invalid option: " + args[index] + "\n"); return; } switch (args[index][1]) { case 'c': options |= XmlDiffOptions.IgnoreComments; break; case 'd': options |= XmlDiffOptions.IgnoreDtd; break; case 'e': flag1 = true; break; case 'f': bFragments = true; break; case 'n': options |= XmlDiffOptions.IgnoreNamespaces; break; case 'o': options |= XmlDiffOptions.IgnoreChildOrder; break; case 'p': options |= XmlDiffOptions.IgnorePI; break; case 'r': options |= XmlDiffOptions.IgnorePrefixes; break; case 't': xmlDiffAlgorithm = XmlDiffAlgorithm.Fast; break; case 'w': options |= XmlDiffOptions.IgnoreWhitespace; break; case 'x': options |= XmlDiffOptions.IgnoreXmlDecl; break; case 'z': xmlDiffAlgorithm = XmlDiffAlgorithm.Precise; break; default: Console.Write("Invalid option: " + args[index] + "\n"); return; } empty += (string)(object)args[index][1]; ++index; if (args.Length - index < 3) { TestXmlDiff.WriteUsage(); return; } } var str1 = args[index]; var str2 = args[index + 1]; var str3 = args[index + 2]; var flag2 = args.Length - index == 4 && args[index + 3] == "verify"; var str4 = str1.Substring(str1.LastIndexOf("\\") + 1) + " & " + str2.Substring(str2.LastIndexOf("\\") + 1) + " -> " + str3.Substring(str3.LastIndexOf("\\") + 1); if (empty != string.Empty) { str4 = str4 + " (" + empty + ")"; } Console.Write(str4.Length >= 60 ? str4 + "\n" + new string(' ', 60) : str4 + new string(' ', 60 - str4.Length)); var diffgramWriter1 = (XmlWriter) new XmlTextWriter(str3, (Encoding) new UnicodeEncoding()); var xmlDiff = new XmlDiff(options); xmlDiff.Algorithm = xmlDiffAlgorithm; bool flag3; if (flag1) { if (bFragments) { Console.Write("Cannot have option 'd' and 'f' together."); return; } var xmlDocument1 = new XmlDocument(); xmlDocument1.Load(str1); var xmlDocument2 = new XmlDocument(); xmlDocument2.Load(str2); flag3 = xmlDiff.Compare((XmlNode)xmlDocument1, (XmlNode)xmlDocument2, diffgramWriter1); } else { flag3 = xmlDiff.Compare(str1, str2, bFragments, diffgramWriter1); } if (flag3) { Console.Write("identical"); } else { Console.Write("different"); } diffgramWriter1.Close(); if (!flag3 && flag2) { XmlNode sourceNode; if (bFragments) { var nameTable = new NameTable(); var xmlTextReader = new XmlTextReader((Stream) new FileStream(str1, FileMode.Open, FileAccess.Read), XmlNodeType.Element, new XmlParserContext((XmlNameTable)nameTable, new XmlNamespaceManager((XmlNameTable)nameTable), string.Empty, XmlSpace.Default)); var xmlDocument = new XmlDocument(); var documentFragment = xmlDocument.CreateDocumentFragment(); XmlNode newChild; while ((newChild = xmlDocument.ReadNode((XmlReader)xmlTextReader)) != null) { if (newChild.NodeType != XmlNodeType.Whitespace) { documentFragment.AppendChild(newChild); } } sourceNode = (XmlNode)documentFragment; } else { var xmlDocument = new XmlDocument(); xmlDocument.XmlResolver = (XmlResolver)null; xmlDocument.Load(str1); sourceNode = (XmlNode)xmlDocument; } new XmlPatch().Patch(ref sourceNode, (XmlReader) new XmlTextReader(str3)); if (sourceNode.NodeType == XmlNodeType.Document) { ((XmlDocument)sourceNode).Save("_patched.xml"); } else { var xmlTextWriter = new XmlTextWriter("_patched.xml", Encoding.Unicode); sourceNode.WriteTo((XmlWriter)xmlTextWriter); xmlTextWriter.Close(); } var diffgramWriter2 = (XmlWriter) new XmlTextWriter("_2ndDiff.xml", (Encoding) new UnicodeEncoding()); if (xmlDiff.Compare("_patched.xml", str2, bFragments, diffgramWriter2)) { Console.Write(" - ok"); } else { Console.Write(" - FAILED"); } diffgramWriter2.Close(); } Console.Write("\n"); } catch (Exception ex) { Console.Write("\n*** Error: " + ex.Message + " (source: " + ex.Source + ")\n"); } if (!Debugger.IsAttached) { return; } Console.Write("\nPress enter...\n"); Console.Read(); }
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(); } }
internal Diffgram(XmlDiff xmlDiff) : base(0UL) { this._xmlDiff = xmlDiff; }
// Methods internal override void WriteTo( XmlWriter xmlWriter, XmlDiff xmlDiff ) { xmlWriter.WriteStartElement( XmlDiff.Prefix, "remove", XmlDiff.NamespaceUri ); xmlWriter.WriteAttributeString( "match", _sourceNode.GetRelativeAddress() ); if ( !_bSubtree ) xmlWriter.WriteAttributeString( "subtree", "no" ); if ( _operationID != 0 ) xmlWriter.WriteAttributeString( "opid", _operationID.ToString() ); WriteChildrenTo( xmlWriter, xmlDiff ); xmlWriter.WriteEndElement(); }
// Methods internal override void WriteTo( XmlWriter xmlWriter, XmlDiff xmlDiff ) { xmlWriter.WriteStartElement( XmlDiff.Prefix, "node", XmlDiff.NamespaceUri ); xmlWriter.WriteAttributeString( "match", _sourceNode.GetRelativeAddress() ); WriteChildrenTo( xmlWriter, xmlDiff ); xmlWriter.WriteEndElement(); }
// compares the node to another one and returns the xmldiff operation for changing this node to the other internal override XmlDiffOperation GetDiffOperation(XmlDiffNode changedNode, XmlDiff xmlDiff) { Debug.Assert(false, "This method should be never called."); return(XmlDiffOperation.Undefined); }
private void DoCompare(string changed) { CleanupTempFiles(); XmlDocument original = this.model.Document; XmlDocument doc = new XmlDocument(); XmlReaderSettings settings = model.GetReaderSettings(); using (XmlReader reader = XmlReader.Create(changed, settings)) { doc.Load(reader); } string startupPath = Application.StartupPath; //output diff file. string diffFile = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".xml"); this.tempFiles.AddFile(diffFile, false); bool isEqual = false; 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 = XmlDiffOptions.None; } if (isEqual) { //This means the files were identical for given options. MessageBox.Show(this, SR.FilesAreIdenticalPrompt, SR.FilesAreIdenticalCaption, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } string tempFile = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".htm"); tempFiles.AddFile(tempFile, false); using (XmlReader diffGram = XmlReader.Create(diffFile, settings)) { XmlDiffView diffView = new XmlDiffView(); diffView.Load(new XmlNodeReader(original), diffGram); using (TextWriter htmlWriter = new StreamWriter(tempFile)) { SideBySideXmlNotepadHeader(this.model.FileName, changed, htmlWriter); diffView.GetHtml(htmlWriter); } } /* Uri uri = new Uri(tempFile); WebBrowserForm browserForm = new WebBrowserForm(uri, "XmlDiff"); browserForm.Show(); */ }
private ulong ComputeHashXmlNode(XmlNode node) { switch (node.NodeType) { case XmlNodeType.Element: { XmlElement el = (XmlElement)node; HashAlgorithm ha = new HashAlgorithm(); HashElement(ha, el.LocalName, el.Prefix, el.NamespaceURI); ComputeHashXmlChildren(ha, el); return(ha.Hash); } case XmlNodeType.Attribute: // attributes are hashed in ComputeHashXmlChildren; Debug.Assert(false); return(0); case XmlNodeType.Whitespace: return(0); case XmlNodeType.SignificantWhitespace: if (!_bIgnoreWhitespace) { goto case XmlNodeType.Text; } return(0); case XmlNodeType.Comment: if (!_bIgnoreComments) { return(HashCharacterNode(XmlNodeType.Comment, ((XmlCharacterData)node).Value)); } return(0); case XmlNodeType.Text: { XmlCharacterData cd = (XmlCharacterData)node; if (_bIgnoreWhitespace) { return(HashCharacterNode(cd.NodeType, XmlDiff.NormalizeText(cd.Value))); } else { return(HashCharacterNode(cd.NodeType, cd.Value)); } } case XmlNodeType.CDATA: { XmlCharacterData cd = (XmlCharacterData)node; return(HashCharacterNode(cd.NodeType, cd.Value)); } case XmlNodeType.ProcessingInstruction: { if (_bIgnorePI) { return(0); } XmlProcessingInstruction pi = (XmlProcessingInstruction)node; return(HashPI(pi.Target, pi.Value)); } case XmlNodeType.EntityReference: { #if NETCORE throw new NotSupportedException("XmlNodeType.EntityReference is not supported"); #else XmlEntityReference er = (XmlEntityReference)node; return(HashER(er.Name)); #endif } case XmlNodeType.XmlDeclaration: { if (_bIgnoreXmlDecl) { return(0); } XmlDeclaration decl = (XmlDeclaration)node; return(HashXmlDeclaration(XmlDiff.NormalizeXmlDeclaration(decl.Value))); } case XmlNodeType.DocumentType: { if (_bIgnoreDtd) { return(0); } #if NETCORE throw new NotSupportedException("XmlNodeType.DocumentType is not supported"); #else XmlDocumentType docType = (XmlDocumentType)node; return(HashDocumentType(docType.Name, docType.PublicId, docType.SystemId, docType.InternalSubset)); #endif } case XmlNodeType.DocumentFragment: return(0); default: Debug.Assert(false); return(0); } }
private void ComputeHashXmlChildren(HashAlgorithm ha, XmlNode parent) { XmlElement el = parent as XmlElement; if (el != null) { ulong attrHashSum = 0; int attrsCount = 0; XmlAttributeCollection attrs = ((XmlElement)parent).Attributes; for (int i = 0; i < attrs.Count; i++) { XmlAttribute attr = (XmlAttribute)attrs.Item(i); ulong hashValue = 0; // default namespace def if (attr.LocalName == "xmlns" && attr.Prefix == string.Empty) { if (_bIgnoreNamespaces) { continue; } hashValue = HashNamespace(string.Empty, attr.Value); } // namespace def else if (attr.Prefix == "xmlns") { if (_bIgnoreNamespaces) { continue; } hashValue = HashNamespace(attr.LocalName, attr.Value); } // attribute else { if (_bIgnoreWhitespace) { hashValue = HashAttribute(attr.LocalName, attr.Prefix, attr.NamespaceURI, XmlDiff.NormalizeText(attr.Value)); } else { hashValue = HashAttribute(attr.LocalName, attr.Prefix, attr.NamespaceURI, attr.Value); } } Debug.Assert(hashValue != 0); attrsCount++; attrHashSum += hashValue; } if (attrsCount != 0) { ha.AddULong(attrHashSum); ha.AddInt(attrsCount); } } int childrenCount = 0; if (_bIgnoreChildOrder) { ulong totalHashSum = 0; XmlNode curChild = parent.FirstChild; while (curChild != null) { ulong hashValue = ComputeHashXmlNode(curChild); if (hashValue != 0) { totalHashSum += hashValue; childrenCount++; } curChild = curChild.NextSibling; } ha.AddULong(totalHashSum); } else { XmlNode curChild = parent.FirstChild; while (curChild != null) { ulong hashValue = ComputeHashXmlNode(curChild); if (hashValue != 0) { ha.AddULong(hashValue); childrenCount++; } curChild = curChild.NextSibling; } } if (childrenCount != 0) { ha.AddInt(childrenCount); } }
private void ComputeTreeDistance(int sourcePos, int targetPos) { int sourcePosLeft = _sourceNodes[sourcePos].Left; int targetPosLeft = _targetNodes[targetPos].Left; int i, j; // init borders of _forestDist array EditScriptAddOpened esAdd = new EditScriptAddOpened(targetPosLeft, EmptyEditScript); EditScriptRemoveOpened esRemove = new EditScriptRemoveOpened(sourcePosLeft, EmptyEditScript); _forestDist[sourcePosLeft - 1, targetPosLeft - 1]._cost = 0; _forestDist[sourcePosLeft - 1, targetPosLeft - 1]._editScript = EmptyEditScript; for (i = sourcePosLeft; i <= sourcePos; i++) { _forestDist[i, targetPosLeft - 1]._cost = (i - sourcePosLeft + 1) * OperationCost[(int)XmlDiffOperation.Remove]; _forestDist[i, targetPosLeft - 1]._editScript = esRemove; } for (j = targetPosLeft; j <= targetPos; j++) { _forestDist[sourcePosLeft - 1, j]._cost = (j - targetPosLeft + 1) * OperationCost[(int)XmlDiffOperation.Add]; _forestDist[sourcePosLeft - 1, j]._editScript = esAdd; } #if DEBUG Trace.WriteIf(XmlDiff.T_ForestDistance.Enabled, "\nForest distance (" + sourcePos + "," + targetPos + "):\n"); Trace.WriteIf(XmlDiff.T_ForestDistance.Enabled, " 0 "); for (j = targetPosLeft; j <= targetPos; j++) { Trace.WriteIf(XmlDiff.T_ForestDistance.Enabled, j + " "); } Trace.WriteIf(XmlDiff.T_ForestDistance.Enabled, "\n "); for (j = targetPosLeft - 1; j <= targetPos; j++) { Trace.WriteIf(XmlDiff.T_ForestDistance.Enabled, "*****"); } Trace.WriteIf(XmlDiff.T_ForestDistance.Enabled, "\n0 * 0 "); for (j = targetPosLeft; j <= targetPos; j++) { Trace.WriteIf(XmlDiff.T_ForestDistance.Enabled, "-" + _forestDist[sourcePosLeft - 1, j]._cost + " "); } Trace.WriteIf(XmlDiff.T_ForestDistance.Enabled, "\n"); #endif // compute the inside of _forestDist array for (i = sourcePosLeft; i <= sourcePos; i++) { #if DEBUG Trace.WriteIf(XmlDiff.T_ForestDistance.Enabled, i + " * |" + _forestDist[i, targetPosLeft - 1]._cost + " "); #endif for (j = targetPosLeft; j <= targetPos; j++) { int sourceCurLeft = _sourceNodes[i].Left; int targetCurLeft = _targetNodes[j].Left; int removeCost = _forestDist[i - 1, j]._cost + OperationCost[(int)XmlDiffOperation.Remove]; int addCost = _forestDist[i, j - 1]._cost + OperationCost[(int)XmlDiffOperation.Add]; if (sourceCurLeft == sourcePosLeft && targetCurLeft == targetPosLeft) { XmlDiffOperation changeOp = _sourceNodes[i].GetDiffOperation(_targetNodes[j], _xmlDiff); Debug.Assert(XmlDiff.IsChangeOperation(changeOp) || changeOp == XmlDiffOperation.Match || changeOp == XmlDiffOperation.Undefined); if (changeOp == XmlDiffOperation.Match) { // identical nodes matched OpNodesMatch(i, j); } else { int changeCost = _forestDist[i - 1, j - 1]._cost + OperationCost[(int)changeOp]; if (changeCost < addCost) { // operation 'change' if (changeCost < removeCost) { OpChange(i, j, changeOp, changeCost); } // operation 'remove' else { OpRemove(i, j, removeCost); } } else { // operation 'add' if (addCost < removeCost) { OpAdd(i, j, addCost); } // operation 'remove' else { OpRemove(i, j, removeCost); } } } _treeDist[i, j]._cost = _forestDist[i, j]._cost; _treeDist[i, j]._editScript = _forestDist[i, j]._editScript.GetClosedScript(i, j);; } else { int m = sourceCurLeft - 1; int n = targetCurLeft - 1; if (m < sourcePosLeft - 1) { m = sourcePosLeft - 1; } if (n < targetPosLeft - 1) { n = targetPosLeft - 1; } // cost of concatenating of the two edit scripts int compoundEditCost = _forestDist[m, n]._cost + _treeDist[i, j]._cost; if (compoundEditCost < addCost) { if (compoundEditCost < removeCost) { // copy script if (_treeDist[i, j]._editScript == EmptyEditScript) { Debug.Assert(_treeDist[i, j]._cost == 0); OpCopyScript(i, j, m, n); } // concatenate scripts else { OpConcatScripts(i, j, m, n); } } // operation 'remove' else { OpRemove(i, j, removeCost); } } else { // operation 'add' if (addCost < removeCost) { OpAdd(i, j, addCost); } // operation 'remove' else { OpRemove(i, j, removeCost); } } } #if DEBUG Trace.WriteIf(XmlDiff.T_ForestDistance.Enabled, _forestDist[i, j]._cost + " "); #endif } #if DEBUG Trace.WriteIf(XmlDiff.T_ForestDistance.Enabled, "\n"); #endif } }
internal override void WriteTo(XmlWriter xmlWriter, XmlDiff xmlDiff) { xmlWriter.WriteStartElement("xd", "add", "http://schemas.microsoft.com/xmltools/2002/xmldiff"); switch (this._targetNode.NodeType) { case XmlDiffNodeType.XmlDeclaration: xmlWriter.WriteAttributeString("type", 17.ToString()); if (this._operationID != 0UL) { xmlWriter.WriteAttributeString("opid", this._operationID.ToString()); } xmlWriter.WriteString(((XmlDiffXmlDeclaration)this._targetNode).Value); break; case XmlDiffNodeType.DocumentType: xmlWriter.WriteAttributeString("type", 10.ToString()); var targetNode1 = (XmlDiffDocumentType)this._targetNode; if (this._operationID != 0UL) { xmlWriter.WriteAttributeString("opid", this._operationID.ToString()); } xmlWriter.WriteAttributeString("name", targetNode1.Name); if (targetNode1.PublicId != string.Empty) { xmlWriter.WriteAttributeString("publicId", targetNode1.PublicId); } if (targetNode1.SystemId != string.Empty) { xmlWriter.WriteAttributeString("systemId", targetNode1.SystemId); } if (targetNode1.Subset != string.Empty) { xmlWriter.WriteCData(targetNode1.Subset); break; } break; case XmlDiffNodeType.Element: xmlWriter.WriteAttributeString("type", 1.ToString()); var targetNode2 = this._targetNode as XmlDiffElement; xmlWriter.WriteAttributeString("name", targetNode2.LocalName); if (targetNode2.NamespaceURI != string.Empty) { xmlWriter.WriteAttributeString("ns", targetNode2.NamespaceURI); } if (targetNode2.Prefix != string.Empty) { xmlWriter.WriteAttributeString("prefix", targetNode2.Prefix); } if (this._operationID != 0UL) { xmlWriter.WriteAttributeString("opid", this._operationID.ToString()); } this.WriteChildrenTo(xmlWriter, xmlDiff); break; case XmlDiffNodeType.Attribute: xmlWriter.WriteAttributeString("type", 2.ToString()); var targetNode3 = this._targetNode as XmlDiffAttribute; xmlWriter.WriteAttributeString("name", targetNode3.LocalName); if (targetNode3.NamespaceURI != string.Empty) { xmlWriter.WriteAttributeString("ns", targetNode3.NamespaceURI); } if (targetNode3.Prefix != string.Empty) { xmlWriter.WriteAttributeString("prefix", targetNode3.Prefix); } if (this._operationID != 0UL) { xmlWriter.WriteAttributeString("opid", this._operationID.ToString()); } xmlWriter.WriteString(targetNode3.Value); break; case XmlDiffNodeType.Text: xmlWriter.WriteAttributeString("type", ((int)this._targetNode.NodeType).ToString()); if (this._operationID != 0UL) { xmlWriter.WriteAttributeString("opid", this._operationID.ToString()); } xmlWriter.WriteString((this._targetNode as XmlDiffCharData).Value); break; case XmlDiffNodeType.CDATA: xmlWriter.WriteAttributeString("type", ((int)this._targetNode.NodeType).ToString()); if (this._operationID != 0UL) { xmlWriter.WriteAttributeString("opid", this._operationID.ToString()); } xmlWriter.WriteCData((this._targetNode as XmlDiffCharData).Value); break; case XmlDiffNodeType.EntityReference: xmlWriter.WriteAttributeString("type", 5.ToString()); if (this._operationID != 0UL) { xmlWriter.WriteAttributeString("opid", this._operationID.ToString()); } xmlWriter.WriteAttributeString("name", ((XmlDiffER)this._targetNode).Name); break; case XmlDiffNodeType.ProcessingInstruction: xmlWriter.WriteAttributeString("type", ((int)this._targetNode.NodeType).ToString()); if (this._operationID != 0UL) { xmlWriter.WriteAttributeString("opid", this._operationID.ToString()); } var targetNode4 = this._targetNode as XmlDiffPI; xmlWriter.WriteProcessingInstruction(targetNode4.Name, targetNode4.Value); break; case XmlDiffNodeType.Comment: xmlWriter.WriteAttributeString("type", ((int)this._targetNode.NodeType).ToString()); if (this._operationID != 0UL) { xmlWriter.WriteAttributeString("opid", this._operationID.ToString()); } xmlWriter.WriteComment((this._targetNode as XmlDiffCharData).Value); break; case XmlDiffNodeType.SignificantWhitespace: xmlWriter.WriteAttributeString("type", ((int)this._targetNode.NodeType).ToString()); if (this._operationID != 0UL) { xmlWriter.WriteAttributeString("opid", this._operationID.ToString()); } xmlWriter.WriteString(((XmlDiffCharData)this._targetNode).Value); break; case XmlDiffNodeType.Namespace: xmlWriter.WriteAttributeString("type", 2.ToString()); var targetNode5 = this._targetNode as XmlDiffNamespace; if (targetNode5.Prefix != string.Empty) { xmlWriter.WriteAttributeString("prefix", "xmlns"); xmlWriter.WriteAttributeString("name", targetNode5.Prefix); } else { xmlWriter.WriteAttributeString("name", "xmlns"); } if (this._operationID != 0UL) { xmlWriter.WriteAttributeString("opid", this._operationID.ToString()); } xmlWriter.WriteString(targetNode5.NamespaceURI); break; } xmlWriter.WriteEndElement(); }
// compares the node to another one and returns true, if the nodes are identical; // on elements this method ignores namespace declarations internal virtual bool IsSameAs(XmlDiffNode node, XmlDiff xmlDiff) { return(GetDiffOperation(node, xmlDiff) == XmlDiffOperation.Match); }
private void Patch(ref XmlNode sourceNode, XmlDocument diffDoc) { XmlElement diffgramEl = diffDoc.DocumentElement; if (diffgramEl.LocalName != "xmldiff" || diffgramEl.NamespaceURI != XmlDiff.NamespaceUri) { XmlPatchError.Error(XmlPatchError.ExpectingDiffgramElement); } XmlNamedNodeMap diffgramAttributes = diffgramEl.Attributes; XmlAttribute srcDocAttr = (XmlAttribute)diffgramAttributes.GetNamedItem("srcDocHash"); if (srcDocAttr == null) { XmlPatchError.Error(XmlPatchError.MissingSrcDocAttribute); } ulong hashValue = 0; try { hashValue = ulong.Parse(srcDocAttr.Value); } catch { XmlPatchError.Error(XmlPatchError.InvalidSrcDocAttribute); } XmlAttribute optionsAttr = (XmlAttribute)diffgramAttributes.GetNamedItem("options"); if (optionsAttr == null) { XmlPatchError.Error(XmlPatchError.MissingOptionsAttribute); } // parse options XmlDiffOptions xmlDiffOptions = XmlDiffOptions.None; try { xmlDiffOptions = XmlDiff.ParseOptions(optionsAttr.Value); } catch { XmlPatchError.Error(XmlPatchError.InvalidOptionsAttribute); } _ignoreChildOrder = ((int)xmlDiffOptions & (int)XmlDiffOptions.IgnoreChildOrder) != 0; // Calculate the hash value of source document and check if it agrees with // of srcDocHash attribute value. if (!XmlDiff.VerifySource(sourceNode, hashValue, xmlDiffOptions)) { XmlPatchError.Error(XmlPatchError.SrcDocMismatch); } // Translate diffgram & Apply patch if (sourceNode.NodeType == XmlNodeType.Document) { Patch patch = CreatePatch(sourceNode, diffgramEl); // create temporary root element and move all document children under it XmlDocument sourceDoc = (XmlDocument)sourceNode; XmlElement tempRoot = sourceDoc.CreateElement("tempRoot"); XmlNode child = sourceDoc.FirstChild; while (child != null) { XmlNode tmpChild = child.NextSibling; if (child.NodeType != XmlNodeType.XmlDeclaration && child.NodeType != XmlNodeType.DocumentType) { sourceDoc.RemoveChild(child); tempRoot.AppendChild(child); } child = tmpChild; } sourceDoc.AppendChild(tempRoot); // Apply patch XmlNode temp = null; patch.Apply(tempRoot, ref temp); // remove the temporary root element if (sourceNode.NodeType == XmlNodeType.Document) { sourceDoc.RemoveChild(tempRoot); Debug.Assert(tempRoot.Attributes.Count == 0); while ((child = tempRoot.FirstChild) != null) { tempRoot.RemoveChild(child); sourceDoc.AppendChild(child); } } } else if (sourceNode.NodeType == XmlNodeType.DocumentFragment) { Patch patch = CreatePatch(sourceNode, diffgramEl); XmlNode temp = null; patch.Apply(sourceNode, ref temp); } else { // create fragment with sourceNode as its only child XmlDocumentFragment fragment = sourceNode.OwnerDocument.CreateDocumentFragment(); XmlNode previousSourceParent = sourceNode.ParentNode; XmlNode previousSourceSibbling = sourceNode.PreviousSibling; if (previousSourceParent != null) { previousSourceParent.RemoveChild(sourceNode); } if (sourceNode.NodeType != XmlNodeType.XmlDeclaration) { fragment.AppendChild(sourceNode); } else { fragment.InnerXml = sourceNode.OuterXml; } Patch patch = CreatePatch(fragment, diffgramEl); XmlNode temp = null; patch.Apply(fragment, ref temp); XmlNodeList childNodes = fragment.ChildNodes; if (childNodes.Count != 1) { XmlPatchError.Error(XmlPatchError.InternalErrorMoreThanOneNodeLeft, childNodes.Count.ToString()); } sourceNode = childNodes.Item(0); fragment.RemoveAll(); if (previousSourceParent != null) { previousSourceParent.InsertAfter(sourceNode, previousSourceSibbling); } } }
internal XmlDiffDocument(XmlDiff xmlDiff) : base(0) { this._bLoaded = false; this._XmlDiff = xmlDiff; }
private static void CompareXml(string actualFileLocation, string expectedFileName) { Contract.Requires(!String.IsNullOrEmpty(actualFileLocation)); Contract.Requires(!String.IsNullOrEmpty(expectedFileName)); Contract.Requires(File.Exists(actualFileLocation)); var actualFile = new XmlDocument(); actualFile.Load(actualFileLocation); var expectedFile = new XmlDocument(); expectedFile.Load(Assembly.GetExecutingAssembly().GetManifestResourceStream("Oddleif.RunKeeper.Client.Test.ExpectedOutput." + expectedFileName)); var diff = new XmlDiff(); Assert.IsTrue(diff.Compare(expectedFile.DocumentElement, actualFile.DocumentElement)); }
internal override void WriteToXmlReadable(XmlWriter xmlWriter, XmlDiff xmlDiff) { _xmlDiff = xmlDiff; WriteToXmlReadable(xmlWriter); }
internal XmlDiffNode LoadNode(XmlNode node, ref int childPosition) { switch (node.NodeType) { case XmlNodeType.Element: XmlDiffElement elem = new XmlDiffElement(++childPosition, node.LocalName, node.Prefix, node.NamespaceURI); LoadChildNodes(elem, node); elem.ComputeHashValue(_xmlHash); return(elem); case XmlNodeType.Attribute: Debug.Assert(false, "Attributes cannot be loaded by this method."); return(null); case XmlNodeType.Text: string textValue = (_XmlDiff.IgnoreWhitespace) ? XmlDiff.NormalizeText(node.Value) : node.Value; XmlDiffCharData text = new XmlDiffCharData(++childPosition, textValue, XmlDiffNodeType.Text); text.ComputeHashValue(_xmlHash); return(text); case XmlNodeType.CDATA: XmlDiffCharData cdata = new XmlDiffCharData(++childPosition, node.Value, XmlDiffNodeType.CDATA); cdata.ComputeHashValue(_xmlHash); return(cdata); case XmlNodeType.EntityReference: XmlDiffER er = new XmlDiffER(++childPosition, node.Name); er.ComputeHashValue(_xmlHash); return(er); case XmlNodeType.Comment: ++childPosition; if (_XmlDiff.IgnoreComments) { return(null); } XmlDiffCharData comment = new XmlDiffCharData(childPosition, node.Value, XmlDiffNodeType.Comment); comment.ComputeHashValue(_xmlHash); return(comment); case XmlNodeType.ProcessingInstruction: ++childPosition; if (_XmlDiff.IgnorePI) { return(null); } XmlDiffPI pi = new XmlDiffPI(childPosition, node.Name, node.Value); pi.ComputeHashValue(_xmlHash); return(pi); case XmlNodeType.SignificantWhitespace: ++childPosition; if (_XmlDiff.IgnoreWhitespace) { return(null); } XmlDiffCharData ws = new XmlDiffCharData(childPosition, node.Value, XmlDiffNodeType.SignificantWhitespace); ws.ComputeHashValue(_xmlHash); return(ws); case XmlNodeType.XmlDeclaration: ++childPosition; if (_XmlDiff.IgnoreXmlDecl) { return(null); } XmlDiffXmlDeclaration xmlDecl = new XmlDiffXmlDeclaration(childPosition, XmlDiff.NormalizeXmlDeclaration(node.Value)); xmlDecl.ComputeHashValue(_xmlHash); return(xmlDecl); case XmlNodeType.EndElement: return(null); case XmlNodeType.DocumentType: childPosition++; if (_XmlDiff.IgnoreDtd) { return(null); } #if NETCORE throw new NotSupportedException("XmlNodeType.DocumentType is not supported."); #else XmlDocumentType docType = (XmlDocumentType)node; XmlDiffDocumentType diffDocType = new XmlDiffDocumentType(childPosition, docType.Name, docType.PublicId, docType.SystemId, docType.InternalSubset); diffDocType.ComputeHashValue(_xmlHash); return(diffDocType); #endif default: Debug.Assert(false); return(null); } }
// Methods internal override void WriteTo( XmlWriter xmlWriter, XmlDiff xmlDiff ) { xmlWriter.WriteStartElement( XmlDiff.Prefix, "remove", XmlDiff.NamespaceUri ); GetAddressOfAttributeInterval( _attributes, xmlWriter ); Debug.Assert( _operationID == 0 ); xmlWriter.WriteEndElement(); }
// Loads child nodes of the 'parent' node internal void LoadChildNodes(XmlDiffParentNode parent, XmlNode parentDomNode) { XmlDiffNode savedLastChild = _curLastChild; _curLastChild = null; // load attributes & namespace nodes XmlNamedNodeMap attribs = parentDomNode.Attributes; if (attribs != null && attribs.Count > 0) { IEnumerator attrEnum = attribs.GetEnumerator(); while (attrEnum.MoveNext()) { XmlAttribute attr = (XmlAttribute)attrEnum.Current; if (attr.Prefix == "xmlns") { if (!_XmlDiff.IgnoreNamespaces) { XmlDiffNamespace nsNode = new XmlDiffNamespace(attr.LocalName, attr.Value); nsNode.ComputeHashValue(_xmlHash); InsertAttributeOrNamespace((XmlDiffElement)parent, nsNode); } } else if (attr.Prefix == string.Empty && attr.LocalName == "xmlns") { if (!_XmlDiff.IgnoreNamespaces) { XmlDiffNamespace nsNode = new XmlDiffNamespace(string.Empty, attr.Value); nsNode.ComputeHashValue(_xmlHash); InsertAttributeOrNamespace((XmlDiffElement)parent, nsNode); } } else { string attrValue = _XmlDiff.IgnoreWhitespace ? XmlDiff.NormalizeText(attr.Value) : attr.Value; XmlDiffAttribute newAttr = new XmlDiffAttribute(attr.LocalName, attr.Prefix, attr.NamespaceURI, attrValue); newAttr.ComputeHashValue(_xmlHash); InsertAttributeOrNamespace((XmlDiffElement)parent, newAttr); } } } // load children XmlNodeList children = parentDomNode.ChildNodes; if (children.Count == 0) { goto End; } int childPosition = 0; IEnumerator childEnum = children.GetEnumerator(); while (childEnum.MoveNext()) { XmlNode node = (XmlNode)childEnum.Current; // ignore whitespaces between nodes if (node.NodeType == XmlNodeType.Whitespace) { continue; } XmlDiffNode newDiffNode = LoadNode((XmlNode)childEnum.Current, ref childPosition); if (newDiffNode != null) { InsertChild(parent, newDiffNode); } } End: _curLastChild = savedLastChild; }
// Constructor internal Diffgram(XmlDiff xmlDiff) : base(0) { _xmlDiff = xmlDiff; }
internal override void WriteTo(XmlWriter xmlWriter, XmlDiff xmlDiff) { this._xmlDiff = xmlDiff; this.WriteTo(xmlWriter); }
internal override void WriteTo(XmlWriter xmlWriter, XmlDiff xmlDiff) { _xmlDiff = xmlDiff; WriteTo(xmlWriter); }
// Loads child nodes of the 'parent' node internal void LoadChildNodes(XmlDiffParentNode parent, XmlReader reader, bool bEmptyElement) { XmlDiffNode savedLastChild = _curLastChild; _curLastChild = null; // load attributes & namespace nodes while (reader.MoveToNextAttribute()) { if (reader.Prefix == "xmlns") { if (!_XmlDiff.IgnoreNamespaces) { XmlDiffNamespace nsNode = new XmlDiffNamespace(reader.LocalName, reader.Value); nsNode.ComputeHashValue(_xmlHash); InsertAttributeOrNamespace((XmlDiffElement)parent, nsNode); } } else if (reader.Prefix == string.Empty && reader.LocalName == "xmlns") { if (!_XmlDiff.IgnoreNamespaces) { XmlDiffNamespace nsNode = new XmlDiffNamespace(string.Empty, reader.Value); nsNode.ComputeHashValue(_xmlHash); InsertAttributeOrNamespace((XmlDiffElement)parent, nsNode); } } else { string attrValue = _XmlDiff.IgnoreWhitespace ? XmlDiff.NormalizeText(reader.Value) : reader.Value; XmlDiffAttribute attr = new XmlDiffAttribute(reader.LocalName, reader.Prefix, reader.NamespaceURI, attrValue); attr.ComputeHashValue(_xmlHash); InsertAttributeOrNamespace((XmlDiffElement)parent, attr); } } // empty element -> return, do not load chilren if (bEmptyElement) { goto End; } int childPosition = 0; // load children if (!reader.Read()) { goto End; } do { // ignore whitespaces between nodes if (reader.NodeType == XmlNodeType.Whitespace) { continue; } switch (reader.NodeType) { case XmlNodeType.Element: { bool bEmptyEl = reader.IsEmptyElement; XmlDiffElement elem = new XmlDiffElement(++childPosition, reader.LocalName, reader.Prefix, reader.NamespaceURI); LoadChildNodes(elem, reader, bEmptyEl); elem.ComputeHashValue(_xmlHash); InsertChild(parent, elem); break; } case XmlNodeType.Attribute: { Debug.Assert(false, "We should never get to this point, attributes should be read at the beginning of thid method."); break; } case XmlNodeType.Text: { string textValue = (_XmlDiff.IgnoreWhitespace) ? XmlDiff.NormalizeText(reader.Value) : reader.Value; XmlDiffCharData charDataNode = new XmlDiffCharData(++childPosition, textValue, XmlDiffNodeType.Text); charDataNode.ComputeHashValue(_xmlHash); InsertChild(parent, charDataNode); break; } case XmlNodeType.CDATA: { XmlDiffCharData charDataNode = new XmlDiffCharData(++childPosition, reader.Value, XmlDiffNodeType.CDATA); charDataNode.ComputeHashValue(_xmlHash); InsertChild(parent, charDataNode); break; } case XmlNodeType.EntityReference: { XmlDiffER er = new XmlDiffER(++childPosition, reader.Name); er.ComputeHashValue(_xmlHash); InsertChild(parent, er); break; } case XmlNodeType.Comment: { ++childPosition; if (!_XmlDiff.IgnoreComments) { XmlDiffCharData charDataNode = new XmlDiffCharData(childPosition, reader.Value, XmlDiffNodeType.Comment); charDataNode.ComputeHashValue(_xmlHash); InsertChild(parent, charDataNode); } break; } case XmlNodeType.ProcessingInstruction: { ++childPosition; if (!_XmlDiff.IgnorePI) { XmlDiffPI pi = new XmlDiffPI(childPosition, reader.Name, reader.Value); pi.ComputeHashValue(_xmlHash); InsertChild(parent, pi); } break; } case XmlNodeType.SignificantWhitespace: { if (reader.XmlSpace == XmlSpace.Preserve) { ++childPosition; if (!_XmlDiff.IgnoreWhitespace) { XmlDiffCharData charDataNode = new XmlDiffCharData(childPosition, reader.Value, XmlDiffNodeType.SignificantWhitespace); charDataNode.ComputeHashValue(_xmlHash); InsertChild(parent, charDataNode); } } break; } case XmlNodeType.XmlDeclaration: { ++childPosition; if (!_XmlDiff.IgnoreXmlDecl) { XmlDiffXmlDeclaration xmlDecl = new XmlDiffXmlDeclaration(childPosition, XmlDiff.NormalizeXmlDeclaration(reader.Value)); xmlDecl.ComputeHashValue(_xmlHash); InsertChild(parent, xmlDecl); } break; } case XmlNodeType.EndElement: goto End; case XmlNodeType.DocumentType: childPosition++; if (!_XmlDiff.IgnoreDtd) { XmlDiffDocumentType docType = new XmlDiffDocumentType(childPosition, reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), reader.Value); docType.ComputeHashValue(_xmlHash); InsertChild(parent, docType); } break; default: Debug.Assert(false); break; } } while (reader.Read()); End: _curLastChild = savedLastChild; }
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(); } }
// compares the node to another one and returns the xmldiff operation for changing this node to the other one internal abstract XmlDiffOperation GetDiffOperation(XmlDiffNode changedNode, XmlDiff xmlDiff);
private void CompareResults(String name) { PdfReader reader = new PdfReader(OUT + name + ".pdf"); string orig = RESOURCES + "xml\\test" + name + ".xml"; string curr = TARGET + "xml\\test" + name + ".xml"; FileStream xmlOut = new FileStream(curr, FileMode.Create); new MyTaggedPdfReaderTool().ConvertToXml(reader, xmlOut); xmlOut.Close(); XmlDiff xmldiff = new XmlDiff(XmlDiffOptions.None); Assert.True(xmldiff.Compare(orig, curr, false)); }
private void CompareResults(String orig, String curr) { PdfReader cmpReader = new PdfReader(CMP_FOLDER + orig); PdfReader outReader = new PdfReader(OUT_FOLDER + curr); byte[] cmpBytes = cmpReader.Metadata, outBytes = outReader.Metadata; IXmpMeta xmpMeta = XmpMetaFactory.ParseFromBuffer(cmpBytes); XmpUtils.RemoveProperties(xmpMeta, XmpConst.NS_XMP, XmpBasicProperties.CREATEDATE, true, true); XmpUtils.RemoveProperties(xmpMeta, XmpConst.NS_XMP, XmpBasicProperties.MODIFYDATE, true, true); XmpUtils.RemoveProperties(xmpMeta, XmpConst.NS_XMP, XmpBasicProperties.METADATADATE, true, true); XmpUtils.RemoveProperties(xmpMeta, XmpConst.NS_PDF, PdfProperties.PRODUCER, true, true); cmpBytes = XmpMetaFactory.SerializeToBuffer(xmpMeta, new SerializeOptions(SerializeOptions.SORT)); xmpMeta = XmpMetaFactory.ParseFromBuffer(outBytes); XmpUtils.RemoveProperties(xmpMeta, XmpConst.NS_XMP, XmpBasicProperties.CREATEDATE, true, true); XmpUtils.RemoveProperties(xmpMeta, XmpConst.NS_XMP, XmpBasicProperties.MODIFYDATE, true, true); XmpUtils.RemoveProperties(xmpMeta, XmpConst.NS_XMP, XmpBasicProperties.METADATADATE, true, true); XmpUtils.RemoveProperties(xmpMeta, XmpConst.NS_PDF, PdfProperties.PRODUCER, true, true); outBytes = XmpMetaFactory.SerializeToBuffer(xmpMeta, new SerializeOptions(SerializeOptions.SORT)); XmlDiff xmldiff = new XmlDiff(XmlDiffOptions.None); if (!xmldiff.Compare(new XmlTextReader(new MemoryStream(cmpBytes)), new XmlTextReader(new MemoryStream(outBytes)))) { String currXmlName = curr.Replace(".pdf", ".xml"); FileStream outStream = new FileStream(OUT_FOLDER + "cmp_" + currXmlName, FileMode.Create); outStream.Write(cmpBytes, 0, cmpBytes.Length); outStream = new FileStream(OUT_FOLDER + currXmlName, FileMode.Create); outStream.Write(outBytes, 0, outBytes.Length); Assert.Fail("The XMP packages are different!!!"); } }
internal override void WriteTo(XmlWriter xmlWriter, XmlDiff xmlDiff) { xmlWriter.WriteStartElement("xd", "change", "http://schemas.microsoft.com/xmltools/2002/xmldiff"); xmlWriter.WriteAttributeString("match", this._sourceNode.GetRelativeAddress()); if (this._operationID != 0UL) { xmlWriter.WriteAttributeString("opid", this._operationID.ToString()); } switch (this._op) { case XmlDiffOperation.ChangeElementName: var sourceNode1 = (XmlDiffElement)this._sourceNode; var targetNode1 = (XmlDiffElement)this._targetNode; if (sourceNode1.LocalName != targetNode1.LocalName) { xmlWriter.WriteAttributeString("name", targetNode1.LocalName); } if (sourceNode1.Prefix != targetNode1.Prefix && !xmlDiff.IgnorePrefixes && !xmlDiff.IgnoreNamespaces) { xmlWriter.WriteAttributeString("prefix", targetNode1.Prefix); } if (sourceNode1.NamespaceURI != targetNode1.NamespaceURI && !xmlDiff.IgnoreNamespaces) { xmlWriter.WriteAttributeString("ns", targetNode1.NamespaceURI); } this.WriteChildrenTo(xmlWriter, xmlDiff); break; case XmlDiffOperation.ChangePI: var sourceNode2 = (XmlDiffPI)this._sourceNode; var targetNode2 = (XmlDiffPI)this._targetNode; if (sourceNode2.Value == targetNode2.Value) { xmlWriter.WriteAttributeString("name", targetNode2.Name); break; } xmlWriter.WriteProcessingInstruction(targetNode2.Name, targetNode2.Value); break; case XmlDiffOperation.ChangeER: xmlWriter.WriteAttributeString("name", ((XmlDiffER)this._targetNode).Name); break; case XmlDiffOperation.ChangeCharacterData: var targetNode3 = (XmlDiffCharData)this._targetNode; switch (this._targetNode.NodeType) { case XmlDiffNodeType.Text: case XmlDiffNodeType.SignificantWhitespace: xmlWriter.WriteString(targetNode3.Value); break; case XmlDiffNodeType.CDATA: xmlWriter.WriteCData(targetNode3.Value); break; case XmlDiffNodeType.Comment: xmlWriter.WriteComment(targetNode3.Value); break; } break; case XmlDiffOperation.ChangeXmlDeclaration: xmlWriter.WriteString(((XmlDiffXmlDeclaration)this._targetNode).Value); break; case XmlDiffOperation.ChangeDTD: var sourceNode3 = (XmlDiffDocumentType)this._sourceNode; var targetNode4 = (XmlDiffDocumentType)this._targetNode; if (sourceNode3.Name != targetNode4.Name) { xmlWriter.WriteAttributeString("name", targetNode4.Name); } if (sourceNode3.SystemId != targetNode4.SystemId) { xmlWriter.WriteAttributeString("systemId", targetNode4.SystemId); } if (sourceNode3.PublicId != targetNode4.PublicId) { xmlWriter.WriteAttributeString("publicId", targetNode4.PublicId); } if (sourceNode3.Subset != targetNode4.Subset) { xmlWriter.WriteCData(targetNode4.Subset); break; } break; case XmlDiffOperation.ChangeAttr: var sourceNode4 = (XmlDiffAttribute)this._sourceNode; var targetNode5 = (XmlDiffAttribute)this._targetNode; if (sourceNode4.Prefix != targetNode5.Prefix && !xmlDiff.IgnorePrefixes && !xmlDiff.IgnoreNamespaces) { xmlWriter.WriteAttributeString("prefix", targetNode5.Prefix); } if (sourceNode4.NamespaceURI != targetNode5.NamespaceURI && !xmlDiff.IgnoreNamespaces) { xmlWriter.WriteAttributeString("ns", targetNode5.NamespaceURI); } xmlWriter.WriteString(targetNode5.Value); break; } xmlWriter.WriteEndElement(); }
internal override void WriteTo( XmlWriter xmlWriter, XmlDiff xmlDiff ) { _xmlDiff = xmlDiff; WriteTo( xmlWriter ); }
/// <summary> /// Invokes the XmlDiff Compare method. The strings attribute order and whitespace are ignored. /// </summary> /// <param name="diffs">The raw byte array of "diffgram" XML returned.</param> /// <param name="same">True if the two xml strings are identical.</param> /// <returns>Number of bytes read.</returns> private int Compare(out byte [] diffs, out bool same) { Encoding enc = Encoding.UTF8; //.Unicode; System.IO.Stream stream = new System.IO.MemoryStream(); XmlDiff xDiff = new XmlDiff(XmlDiffOptions.IgnoreWhitespace); XmlWriter writer = new XmlTextWriter(stream, enc); same = xDiff.Compare(m_baseReader, m_targetReader, writer); stream.Position = 0; diffs = new Byte[stream.Length]; int bytesRead = stream.Read(diffs,0,(int)stream.Length); writer.Close(); // closes stream too. m_Compared = true; return bytesRead; }
virtual protected bool CompareXmls(String xml1, String xml2) { XmlDiff xmldiff = new XmlDiff(XmlDiffOptions.None); return xmldiff.Compare(xml1, xml2, false); }
// Constructor internal Diffgram( XmlDiff xmlDiff ) : base(0) { _xmlDiff = xmlDiff; }
public bool XmlDiffHtm(string source, string target, string intervalo, string server, string classe) { // Randomiza para criar arquivos unicos de comparação r = new Random(); bool isEqual = false; //Pega o usuário logado... MembershipUser currentUser = Membership.GetUser(); //output diff file. startupPath = ConfigurationManager.AppSettings["XMLData"] + "\\RPTs"; diffFile = startupPath + Path.DirectorySeparatorChar + "vxd" + r.Next() + ".out"; // XmlTextWriter tw = new XmlTextWriter(new StreamWriter(diffFile)); tw.Formatting = Formatting.Indented; try { XmlReader expected = XmlReader.Create(new StringReader(target)); XmlReader actual = XmlReader.Create(new StringReader(source)); XmlDiff diff = new XmlDiff( XmlDiffOptions.IgnoreChildOrder | XmlDiffOptions.IgnoreComments | XmlDiffOptions.IgnoreXmlDecl | XmlDiffOptions.IgnoreWhitespace); isEqual = diff.Compare(actual, expected, tw); tw.Close(); //----------------------------------------------------------------- // Cria a comparação dos XMLs... XmlDiffView dv = new XmlDiffView(); // Carrega o arquivo orig = source + o arquivo XML das Diff... XmlTextReader orig = new XmlTextReader(new StringReader(source)); //source XmlTextReader diffGram = new XmlTextReader(diffFile); dv.Load(orig, diffGram); orig.Close(); diffGram.Close(); // Chama a função para gravar e formatar o conteudo + diff em HTM... if (!isEqual) { GrHtm(dv, intervalo, server, classe); } // return isEqual; } catch (XmlException xe) { divMessage.InnerHtml = "<span id='msg' style='color:#FF3300;font-size:Smaller;font-weight:bold;'>Ocorreu um erro de Comparação - " + xe.StackTrace + "</span>"; return isEqual; } }
// compares the node to another one and returns the xmldiff operation for changing this node to the other internal override XmlDiffOperation GetDiffOperation( XmlDiffNode changedNode, XmlDiff xmlDiff ) { if ( changedNode.NodeType != XmlDiffNodeType.Document ) return XmlDiffOperation.Undefined; else return XmlDiffOperation.Match; }
public void Serialization() { try { XmlDiff diff = new XmlDiff(); TemplateBox templateBox = new TemplateBox(TemplatingResources.TemplatesDefault); String result = templateBox.Serialize(); //Utils.WriteToFile(@"C:\temp\templates.xml", result); diff.IgnoreChildOrder = true; diff.IgnoreComments = true; diff.IgnoreDtd = true; diff.IgnoreNamespaces = true; diff.IgnorePI = true; diff.IgnorePrefixes = true; diff.IgnoreWhitespace = true; diff.IgnoreXmlDecl = true; StringWriter diffgramString = new StringWriter(); XmlTextWriter diffgramXml = new XmlTextWriter(diffgramString); bool diffBool = diff.Compare(new XmlTextReader(new StringReader(result)), new XmlTextReader(new StringReader(TemplatingResources.TemplatesDefault)), diffgramXml); //MessageBox.Show(diffgramString.ToString()); Assert.True(diffBool, diffgramXml.ToString()); } catch (Exception e) { Assert.Fail("Exception: " + e.GetType().Name + "\n" + e.Message + "\n" + e.StackTrace); } }
// Constructor internal DiffgramGenerator( XmlDiff xmlDiff ) { Debug.Assert( xmlDiff != null ); _xmlDiff = xmlDiff; _bChildOrderSignificant = !xmlDiff.IgnoreChildOrder; _lastOperationID = 0; }
private void Compare(String outPdf, String cmpPdf) { CompareTool ct = new CompareTool(outPdf, cmpPdf); Assert.IsNull(ct.Compare(OUT_FOLDER, "difference")); String outXml = Path.GetFileNameWithoutExtension(outPdf); String cmpXml = Path.GetFileNameWithoutExtension(cmpPdf); outXml = OUT_FOLDER + outXml.Replace(".pdf", "") + ".xml"; cmpXml = OUT_FOLDER + "cmp_" + cmpXml.Replace("cmp_", "").Replace(".pdf", "") + ".xml"; PdfReader reader = new PdfReader(outPdf); new MyTaggedPdfReaderTool().ConvertToXml(reader, new FileStream(outXml, FileMode.Create)); reader.Close(); reader = new PdfReader(outPdf); new MyTaggedPdfReaderTool().ConvertToXml(reader, new FileStream(cmpXml, FileMode.Create)); reader.Close(); XmlDiff xmldiff = new XmlDiff(XmlDiffOptions.None); Assert.True(xmldiff.Compare(cmpXml, outXml, false)); }