克隆文档
克隆文档是创建原始文档的相同副本的过程,这可以提高性能并避免潜在的内存泄漏。
本文将解释克隆文档的主要用例以及如何使用Aspose.Words创建文档克隆。
使用克隆文档的操作
克隆操作允许您更快地创建文档,因为您不需要每次都从文件中加载和解析文档。
创建文档的克隆后,您将能够对其进行编辑并对其执行不同的操作,例如,将其与原始文档进行比较,将其追加或插入到另一个文档中。 您还可以在将克隆的元素或其内容插入到另一个文档之前修改它们。
创建文档克隆
Aspose.Words允许您使用Clone方法克隆文档,该方法执行文档的深度副本并返回它。 换句话说,它将获得DOM的完整副本。 Clone
方法加快了文档生成速度,您只需要一行代码就可以获得文档的副本。
克隆生成一个新文档,其内容与原始文档相同,但每个原始文档的nodes的唯一副本。 您还可以使用nodeClone方法将克隆操作应用于文档节点,该方法允许您使用和不使用其子节点复制复合文档节点。
下面的代码示例演示如何克隆文档并在该文档中创建部分的副本:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
// Create a document. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.writeln("This is the original document before applying the clone method"); | |
// Clone the document. | |
Document clone = doc.deepClone(); | |
// Edit the cloned document. | |
builder = new DocumentBuilder(clone); | |
builder.write("Section 1"); | |
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE); | |
builder.write("Section 2"); | |
// This shows what is in the document originally. The document has two sections. | |
System.out.println(clone.getText().trim()); | |
// Duplicate the last section and append the copy to the end of the document. | |
int lastSectionIdx = clone.getSections().getCount() - 1; | |
Section newSection = clone.getSections().get(lastSectionIdx).deepClone(); | |
clone.getSections().add(newSection); | |
// Check what the document contains after we changed it. | |
System.out.println(clone.getText().trim()); |