I am programmly generating new paragraphs in Word document via Open XML SDK 2.0.
A have first paragraphs with properties, that i would like to append to all new generated paragraphs.
Somthing like this:
var _texts = new List<string>() { "Text 1", "Text 2", "Text 1", "Text 4"};
var sdtBlock = wordDoc.MainDocumentPart.RootElement.Descendants<Paragraph>().First();
foreach (string _t in _texts)
{
Paragraph p = new Paragraph();
p.Append(sdtBlock.ParagraphProperties);
p.Append(new Run(new Text(_t)));
sdtBlock.InsertAfterSelf<Paragraph>(p);
}
Executing this code throws an Exception: “Cannot insert the OpenXmlElement “newChild” because it is part of a tree.”
Any ideas?
You need to use the
CloneNode()method to make a copy of the instance ofParagraphPropertiesthat you want to add to your new paragraph, e.g.Otherwise, you’ll get the exception you described (because you would be adding the original node in two different places in the same document, which is not allowed – and not what you were intending to do).