我有两个 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);
基本上我使用它的别名从第一个文档中获取容器(一个 SdtBlock)来识别它,然后获取第二个元素的所有子元素(删除我不想复制的 SectionProperties),然后尝试将它们添加到容器元素。
问题是我遇到了这个异常:
Cannot insert the OpenXmlElement "newChild" because it is part of a tree.
当我调用该代码的最后一行(附加)时。
关于如何实现我想要的任何想法?