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