gpt4 book ai didi

merge - OpenXml:在文档之间复制 OpenXmlElement

转载 作者:行者123 更新时间:2023-12-03 06:56:33 26 4
gpt4 key购买 nike

我有两个 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.

当我调用该代码的最后一行(追加)时。

关于如何实现我想要的东西有什么想法吗?

最佳答案

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

关于merge - OpenXml:在文档之间复制 OpenXmlElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3304870/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com