OpenXml:在文档之间复制 OpenXmlElement
我有两个 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) copy),然后尝试将它们添加到容器元素中。
问题是我遇到了这个异常:
Cannot insert the OpenXmlElement "newChild" because it is part of a tree.
当我调用该代码的最后一行(附加)时。
关于如何实现我想要的任何想法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
elementsToCopy 仍附加到其原始树。所以你必须删除它的父母或复制它们(以保持原始完整)。我认为存在一个removeParent()方法。
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.
您需要克隆元素来复制
containerElement.Append(elementsToCopy.CloneNode(true));
You need to clone the element to copy
containerElement.Append(elementsToCopy.CloneNode(true));