比较文档

比较文档是识别两个文档之间的更改并将更改包含为修订的过程。此过程会比较任何两个文档,包括一个特定文档的版本,然后两个文档之间的更改将显示为第一个文档中的修订版本。

比较方法是通过在字符级别或词级别比较单词来实现的。如果一个单词至少包含一个字符的变化,则在结果中,差异将显示为整个单词的变化,而不是一个字符的变化。这种比较过程是法律和金融行业的常见任务。

您可以使用 Aspose.Words 来比较文档并获取格式、页眉/页脚、表格等方面的内容更改,而不是手动搜索文档之间或不同版本之间的差异。

本文介绍如何比较文档以及如何指定高级比较属性。

限制和支持的文件格式

比较文档是一项非常复杂的功能。内容组合的不同部分需要进行分析以识别所有差异。造成这种复杂性的原因是 Aspose.Words 的目标是获得与 Microsoft Word 比较算法相同的比较结果。

比较两个文档的一般限制是在调用比较方法之前它们不得有修订,因为 Microsoft Word 中存在此限制。

比较两个文档

当您比较文档时,后一个文档与前一个文档的差异会显示为对前一个文档的修订。当您修改文档时,运行比较方法后,每个编辑都会有自己的修订版本。

Aspose.Words 允许您使用 Compare 方法识别文档差异 - 这类似于 Microsoft Word 文档比较功能。它允许您检查文档或文档版本以查找差异和更改,包括格式修改,例如字体更改、间距更改、单词和段落的添加。

作为比较的结果,可以确定文档相等或不相等。术语"同等"文档意味着比较方法无法将更改表示为修订。这意味着文档文本和文本格式是相同的。但文档之间可能还存在其他差异。例如,Microsoft Word 仅支持样式的格式修订,并且不能表示样式插入/删除。因此文档可以有一组不同的样式,并且 Compare 方法仍然不会产生任何修订。

以下代码示例显示如何检查两个文档是否相等:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document docA = new Document(dataDir + "TestFile.doc");
Document docB = new Document(dataDir + "TestFile - Copy.doc");
// DocA now contains changes as revisions.
docA.Compare(docB, "user", DateTime.Now);
if (docA.Revisions.Count == 0)
Console.WriteLine("Documents are equal");
else
Console.WriteLine("Documents are not equal");

以下代码示例展示了如何简单地将 Compare 方法应用于两个文档:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The source document doc1.
Document doc1 = new Document();
DocumentBuilder builder = new DocumentBuilder(doc1);
builder.Writeln("This is the original document.");
// The target document doc2.
Document doc2 = new Document();
builder = new DocumentBuilder(doc2);
builder.Writeln("This is the edited document.");
// If either document has a revision, an exception will be thrown.
if (doc1.Revisions.Count == 0 && doc2.Revisions.Count == 0)
doc1.Compare(doc2, "authorName", DateTime.Now);
// If doc1 and doc2 are different, doc1 now has some revisions after the comparison, which can now be viewed and processed.
Assert.AreEqual(2, doc1.Revisions.Count);
foreach (Revision r in doc1.Revisions)
{
Console.WriteLine($"Revision type: {r.RevisionType}, on a node of type \"{r.ParentNode.NodeType}\"");
Console.WriteLine($"\tChanged text: \"{r.ParentNode.GetText()}\"");
}
// All the revisions in doc1 are differences between doc1 and doc2, so accepting them on doc1 transforms doc1 into doc2.
doc1.Revisions.AcceptAll();
// doc1, when saved, now resembles doc2.
doc1.Save(dataDir + "Document.Compare.docx");
doc1 = new Document(dataDir + "Document.Compare.docx");
Assert.AreEqual(0, doc1.Revisions.Count);
Assert.AreEqual(doc2.GetText().Trim(), doc1.GetText().Trim());

指定高级比较选项

当您想要比较文档时,可以应用 CompareOptions 类的许多不同属性。

例如,Aspose.Words 允许您忽略在对原始文档中某些类型的对象进行比较操作期间所做的更改。您可以通过将对象类型设置为"true"来选择适当的属性,例如 IgnoreHeadersAndFootersIgnoreFormattingIgnoreComments 等。

此外,Aspose.Words 提供 Granularity 属性,您可以使用该属性指定是按字符还是按单词跟踪更改。

另一个常见属性是选择在哪个文档中显示比较更改。例如,Microsoft Word 中的"比较文档对话框"有"显示更改"选项–这也会影响比较结果。 Aspose.Words 提供了用于此目的的 Target 属性。

以下代码示例展示了如何设置高级比较属性:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// Create the original document.
Document docOriginal = new Document();
DocumentBuilder builder = new DocumentBuilder(docOriginal);
// Insert paragraph text with an endnote.
builder.Writeln("Hello world! This is the first paragraph.");
builder.InsertFootnote(FootnoteType.Endnote, "Original endnote text.");
// Insert a table.
builder.StartTable();
builder.InsertCell();
builder.Write("Original cell 1 text");
builder.InsertCell();
builder.Write("Original cell 2 text");
builder.EndTable();
// Insert a textbox.
Shape textBox = builder.InsertShape(ShapeType.TextBox, 150, 20);
builder.MoveTo(textBox.FirstParagraph);
builder.Write("Original textbox contents");
// Insert a DATE field.
builder.MoveTo(docOriginal.FirstSection.Body.AppendParagraph(""));
builder.InsertField(" DATE ");
// Insert a comment.
Comment newComment = new Comment(docOriginal, "John Doe", "J.D.", DateTime.Now);
newComment.SetText("Original comment.");
builder.CurrentParagraph.AppendChild(newComment);
// Insert a header.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Writeln("Original header contents.");
// Create a clone of our document, which we will edit and later compare to the original.
Document docEdited = (Document)docOriginal.Clone(true);
Paragraph firstParagraph = docEdited.FirstSection.Body.FirstParagraph;
// Change the formatting of the first paragraph, change casing of original characters and add text.
firstParagraph.Runs[0].Text = "hello world! this is the first paragraph, after editing.";
firstParagraph.ParagraphFormat.Style = docEdited.Styles[StyleIdentifier.Heading1];
// Edit the footnote.
Footnote footnote = (Footnote)docEdited.GetChild(NodeType.Footnote, 0, true);
footnote.FirstParagraph.Runs[1].Text = "Edited endnote text.";
// Edit the table.
Table table = (Table)docEdited.GetChild(NodeType.Table, 0, true);
table.FirstRow.Cells[1].FirstParagraph.Runs[0].Text = "Edited Cell 2 contents";
// Edit the textbox.
textBox = (Shape)docEdited.GetChild(NodeType.Shape, 0, true);
textBox.FirstParagraph.Runs[0].Text = "Edited textbox contents";
// Edit the DATE field.
FieldDate fieldDate = (FieldDate)docEdited.Range.Fields[0];
fieldDate.UseLunarCalendar = true;
// Edit the comment.
Comment comment = (Comment)docEdited.GetChild(NodeType.Comment, 0, true);
comment.FirstParagraph.Runs[0].Text = "Edited comment.";
// Edit the header.
docEdited.FirstSection.HeadersFooters[HeaderFooterType.HeaderPrimary].FirstParagraph.Runs[0].Text = "Edited header contents.";
// Apply different comparing options.
CompareOptions compareOptions = new CompareOptions();
compareOptions.IgnoreFormatting = false;
compareOptions.IgnoreCaseChanges = false;
compareOptions.IgnoreComments = false;
compareOptions.IgnoreTables = false;
compareOptions.IgnoreFields = false;
compareOptions.IgnoreFootnotes = false;
compareOptions.IgnoreTextboxes = false;
compareOptions.IgnoreHeadersAndFooters = false;
compareOptions.Target = ComparisonTargetType.New;
// compare both documents.
docOriginal.Compare(docEdited, "John Doe", DateTime.Now, compareOptions);
docOriginal.Save(dataDir + "Document.CompareOptions.docx");
docOriginal = new Document(dataDir + "Document.CompareOptions.docx");
// If you set compareOptions to ignore certain types of changes,
// then revisions done on those types of nodes will not appear in the output document.
// You can tell what kind of node a revision was done on by looking at the NodeType of the revision's parent nodes.
Assert.AreNotEqual(compareOptions.IgnoreFormatting, docOriginal.Revisions.Any(rev => rev.RevisionType == RevisionType.FormatChange));
Assert.AreNotEqual(compareOptions.IgnoreCaseChanges, docOriginal.Revisions.Any(s => s.ParentNode.GetText().Contains("hello")));
Assert.AreNotEqual(compareOptions.IgnoreComments, docOriginal.Revisions.Any(rev => HasParentOfType(rev, NodeType.Comment)));
Assert.AreNotEqual(compareOptions.IgnoreTables, docOriginal.Revisions.Any(rev => HasParentOfType(rev, NodeType.Table)));
Assert.AreNotEqual(compareOptions.IgnoreFields, docOriginal.Revisions.Any(rev => HasParentOfType(rev, NodeType.FieldStart)));
Assert.AreNotEqual(compareOptions.IgnoreFootnotes, docOriginal.Revisions.Any(rev => HasParentOfType(rev, NodeType.Footnote)));
Assert.AreNotEqual(compareOptions.IgnoreTextboxes, docOriginal.Revisions.Any(rev => HasParentOfType(rev, NodeType.Shape)));
Assert.AreNotEqual(compareOptions.IgnoreHeadersAndFooters, docOriginal.Revisions.Any(rev => HasParentOfType(rev, NodeType.HeaderFooter)));