文書のクローンを作成する
文書の複製は、元の文書の同一のコピーを作成するプロセスであり、パフォーマンスを向上させ、潜在的なメモリリークからあなたを救うことができます。
この記事では、ドキュメントの複製の主な使用例とAspose.Wordsを使用してドキュメントクローンを作成する方法について説明します。
文書の複製を使用した操作
クローン操作を使用すると、毎回ファイルからドキュメントをロードして解析する必要がないため、ドキュメントを作成するプロセスを高速化できます。
文書のクローンを作成した後、元の文書と比較したり、別の文書に追加したり挿入したりするなど、編集してさまざまな操作を行うことができます。 複製された要素またはそのコンテンツを別のドキュメントに挿入する前に変更することもできます。
ドキュメントクローンの作成
Aspose.Wordsを使用すると、ドキュメントの詳細コピーを実行して返すCloneメソッドを使用してドキュメントを複製できます。 言い換えれば、DOMの完全なコピーを取得します。 Clone
メソッドはドキュメントの生成を高速化し、ドキュメントのコピーを取得するために必要なコードは1行だけです。
複製すると、元の文書と同じ内容を持つ新しい文書が作成されますが、元の文書の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()); |