我有兩個Word文檔(WordprocessingDocument),我想將第一個元素的內容替換爲第二個元素的內容。OpenXml:在文檔之間複製OpenXmlElement
這是我在做什麼現在:
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.
當我調用該代碼(追加)的最後一行。
關於如何實現我想要的任何想法?
從其父中刪除一個元素被刪除(該方法的名稱),並CloneNode(真)是一樣的clone() – 2016-08-30 08:03:10