克隆文档

克隆文档是创建原始文档的相同副本的过程,这可以提高性能并避免潜在的内存泄漏。

本文将解释克隆文档的主要用例以及如何使用Aspose.Words创建文档克隆。

使用克隆文档的操作

克隆操作允许您更快地创建文档,因为您不需要每次都从文件中加载和解析文档。

创建文档的克隆后,您将能够对其进行编辑并对其执行不同的操作,例如,将其与原始文档进行比较,将其追加或插入到另一个文档中。 您还可以在将克隆的元素或其内容插入到另一个文档之前修改它们。

创建文档克隆

Aspose.Words允许您使用Clone方法克隆文档,该方法执行文档的深度副本并返回它。 换句话说,它将获得DOM的完整副本。 Clone方法加快了文档的生成速度,您只需要一行代码就可以获得文档的副本。

克隆生成一个新文档,其内容与原始文档相同,但每个原始文档的nodes的唯一副本。 您还可以使用nodeClone方法将克隆操作应用于文档节点,该方法允许您使用和不使用其子节点复制复合文档节点。

下面的代码示例演示如何克隆文档并在该文档中创建部分的副本:

// Create a Document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->Writeln(u"This is the original document before applying the clone method");
// Clone the document.
System::SharedPtr<Document> clone = doc->Clone();
// Edit the cloned document.
builder = System::MakeObject<DocumentBuilder>(clone);
builder->Write(u"Section 1");
builder->InsertBreak(BreakType::SectionBreakNewPage);
builder->Write(u"Section 2");
// This shows what is in the document originally. The document has two sections.
std::cout << clone->GetText().Trim() << std::endl << std::endl;
// Duplicate the last section and append the copy to the end of the document.
auto lastSectionIdx = clone->get_Sections()->get_Count() - 1;
System::SharedPtr<Section> newSection = clone->get_Sections()->idx_get(lastSectionIdx)->Clone();
clone->get_Sections()->Add(newSection);
// Check what the document contains after we changed it.
std::cout << clone->GetText().Trim() << std::endl << std::endl;