I have two Word documents (WordprocessingDocument), and I want to replace the contents of the element in the first with the contents in the body of the second.
Here is what I am doing right now:
var docA = WordprocessingDocument.Open(docAPath, true);
var docB = WordprocessingDocument.Open(docBPath, true);
var containerElement = docA.MainDocumentPart.Document.Body
.Descendants<SdtBlock>()
.FirstOrDefault(sdt => sdt.SdtProperties.Descendants<SdtAlias>().Any(alias => alias.Val == containerElementName))
.SdtContentBlock;
var elementsToCopy = docB.MainDocument.Part.Document.Body.ChildElements.Where(e => e.LocalName != "sectPr"));
containerElement.RemoveAllChildren();
containerElement.Append(elementsToCopy);
Basically I get the container (SdtBlock) from the first document, using its alias to identify it, and then get all the children of the second element (deleting sections that I don't want to copy), and then try to add those elements of the container.
The problem is that I get this exception:
Cannot insert the OpenXmlElement "newChild" because it is part of a tree.
When I call the last line of this code (Append).
Any ideas on how I can achieve what I want?
source
share