OpenXml:在文档之间复制OpenXmlElement

wil*_*lvv 3 merge ms-word documents openxml openxml-sdk

我有两个Word文档(WordprocessingDocument),我想将第一个元素的内容替换为第二个元素的主体中的内容.

这就是我现在正在做的事情:

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);
Run Code Online (Sandbox Code Playgroud)

基本上我从第一个文档获取容器(一个SdtBlock)使用它的别名来识别它,然后获取第二个元素的所有子元素(删除我不想复制的SectionProperties),然后尝试将它们添加到容器元素.

问题是我得到了这个例外:

Cannot insert the OpenXmlElement "newChild" because it is part of a tree.
Run Code Online (Sandbox Code Playgroud)

当我调用该代码的最后一行(Append)时.

关于如何实现我想要的任何想法?

Dev*_*Tun 7

您需要克隆要复制的元素 containerElement.Append(elementsToCopy.CloneNode(true));