3
votes

I have two Word documents (WordprocessingDocument), and I want to replace the contents of an element in the first with the contents in the body of the second one.

This is what I'm 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 (an SdtBlock) from the first document using its alias to identify it, then get all the children of the second element (removing the SectionProperties which I don't want to copy) and then try to add those to the container element.

The problem is that I'm getting this exception:

Cannot insert the OpenXmlElement "newChild" because it is part of a tree.

When I invoke the last line on that code (the Append).

Any ideas on how can I achieve what I want?

2

2 Answers

8
votes

You need to clone the element to copy containerElement.Append(elementsToCopy.CloneNode(true));

3
votes

The elementsToCopy is still attached to it's original tree. So you would have to remove it's parents or copy them( to keep the original intact). I think there exists a removeParent() method.