开发者

OpenXml: Copy OpenXmlElement between documents

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 co开发者_StackOverflowntainer 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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜