OpenXml:在文档之间复制 OpenXmlElement

发布于 2024-09-11 01:37:33 字数 978 浏览 11 评论 0原文

我有两个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

笔落惊风雨 2024-09-18 01:38:01

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.

晌融 2024-09-18 01:37:55

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文