タイトルが示すように、複数の単語 (.docx) ファイルを 1 つの単語ドキュメントにマージしようとしています。これらのドキュメントはそれぞれ 1 ページの長さです。この実装では、この投稿のコードの一部を使用しています。私が直面している問題は、最初のドキュメントのみが適切に記述され、他のすべての反復で新しいドキュメントが追加されますが、ドキュメントの内容は最初のドキュメントと同じです。
私が使用しているコードは次のとおりです。
//list that holds the file paths
List<String> fileNames = new List<string>();
fileNames.Add("filePath");
fileNames.Add("filePath");
fileNames.Add("filePath");
fileNames.Add("filePath");
fileNames.Add("filePath");
//get the first document
MemoryStream mainStream = new MemoryStream();
byte[] buffer = File.ReadAllBytes(fileNames[0]);
mainStream.Write(buffer, 0, buffer.Length);
using (WordprocessingDocument mainDocument = WordprocessingDocument.Open(mainStream, true))
{
//xml for the new document
XElement newBody = XElement.Parse(mainDocument.MainDocumentPart.Document.Body.OuterXml);
//iterate through eacah file
for (int i = 1; i < fileNames.Count; i++)
{
//read in the document
byte[] tempBuffer = File.ReadAllBytes(fileNames[i]);
WordprocessingDocument tempDocument = WordprocessingDocument.Open(new MemoryStream(tempBuffer), true);
//new documents XML
XElement tempBody = XElement.Parse(tempDocument.MainDocumentPart.Document.Body.OuterXml);
//add the new xml
newBody.Add(tempBody);
string str = newBody.ToString();
//write to the main document and save
mainDocument.MainDocumentPart.Document.Body = new Body(newBody.ToString());
mainDocument.MainDocumentPart.Document.Save();
mainDocument.Package.Flush();
tempBuffer = null;
}
//write entire stream to new file
FileStream fileStream = new FileStream("xmltest.docx", FileMode.Create);
mainStream.WriteTo(fileStream);
//ret = mainStream.ToArray();
mainStream.Close();
mainStream.Dispose();
}
ここでも問題は、作成される新しいドキュメントの内容が最初のドキュメントと同じであることです。したがって、これを実行すると、出力は 5 つの同一ページを持つドキュメントになります。リスト内のドキュメントの順序を入れ替えてみましたが、同じ結果が得られたので、1 つのドキュメントに固有のものではありません。ここで私が間違っていることを誰かが提案できますか? 私はそれを見ていますが、私が見ている行動を説明することはできません. 任意の提案をいただければ幸いです。どうもありがとう!
編集:これは、マージしようとしているドキュメントがカスタム XML パーツで生成されているという事実と関係があるのではないかと考えています。ドキュメント内の Xpath が何らかの形で同じコンテンツを指していると考えています。問題は、これらのドキュメントのそれぞれを開いて適切なコンテンツを表示できることです。問題が発生するのは、それらをマージしたときだけです。