Error with Structured Document Tags

Hi
i develop an application which takes a word-docx with 4 SDT (see attachment)Error with SDTs.zip (20.1 KB)

I use the following code (simplified):
foreach (StructuredDocumentTag sdt in wd.GetChildNodes(NodeType.StructuredDocumentTag, true))
{
try
{
if (sdt.SdtType == SdtType.PlainText|| sdt.SdtType== SdtType.RichText)
{
//Gets the Value to insert into SDT by SDT-Name
Inserts ins = GetFirstInsert(li, sdt.Title, 200);

                    sdt.RemoveAllChildren();
                    Paragraph para = sdt.AppendChild(new Paragraph(wd)) as Paragraph;
                    Run run = new Run(wd, ins.Value);
                    para.AppendChild(run);
                }
            }
            catch (Exception e)
            {
                
            }
        }

Problem: First SDT works fine.SDT 2-4 run into this error when executing the line Paragraph para = sdt.AppendChild(new Paragraph(wd)) as Paragraph;
Error is:Cannot insert a node of this type at this location.

What’s wrong?

Uli

@uboddenberg,

Please first check the Markup-Level of each SDT and then write different codes to add child nodes inside particular SDT. For example, the following code will work in this case:

Document wd = new Document("E:\\Error with SDTs\\Error with SDTs.docx");

foreach (StructuredDocumentTag sdt in wd.GetChildNodes(NodeType.StructuredDocumentTag, true))
{
    try
    {
        if (sdt.SdtType == SdtType.PlainText || sdt.SdtType == SdtType.RichText)
        {
            //Gets the Value to insert into SDT by SDT-Name
            //Inserts ins = GetFirstInsert(li, sdt.Title, 200);

            sdt.RemoveAllChildren();

            Run run = new Run(wd, "ins.Value");
            if (sdt.Level == MarkupLevel.Block)
            {
                Paragraph para = sdt.AppendChild(new Paragraph(wd)) as Paragraph;
                para.AppendChild(run);
            }
            else if (sdt.Level == MarkupLevel.Inline)
            {
                sdt.AppendChild(run);
            }
        }
    }
    catch (Exception e)
    {

    }
}

wd.Save("E:\\Error with SDTs\\19.1.docx");

Works.
Thank You.

Uli