0
votes

I have a requirement to insert 2 tables in word document. I am using the OpenXML API for it. When I try inserting the second table it gives me an error - Cannot insert the OpenXmlElement “newChild” because it is part of a tree.

The following is my code:

if (fieldname.Trim().Equals("Table"))
{
    if (!checkCount)
    {
         var tabRun = new Run(table);
         var anc = field.Ancestors<Paragraph>().FirstOrDefault();
         anc.RemoveAllChildren();
         anc.Append(tabRun);
     }
     else
     {
         var tabRun = table;
         var anc = field.Ancestors<Paragraph>().FirstOrDefault();
         anc.RemoveAllChildren();
         anc.Append(tabRun);
     }
}

Here the flag checkCount would be true when the code would execute for the second time. fieldname refers to the mergefield that will be replaced by the table.

I am unable to figure out the cause of this issue.

1

1 Answers

0
votes

As mentioned here and here, you need to clone the node to insert in advance to handle the issue. The error occurs because you're trying to add a node that's not freshly created, but part of a tree already.