Insert a sdt after a found sdt

Is it possible to insert an sdt after another sdt in an already existing document? for example, if I have logic like the below which is stepping through all of the current document sdt’s

var sdtNodes = target.FirstSection.Body.GetChildNodes(NodeType.StructuredDocumentTag, true);
foreach (StructuredDocumentTag sdt in sdtNodes) 
{
    //…Some kind of logic to identify the node I want
    //-> Insert a new sdt (markup type block)? after the found node
}

I’ve tried sdt.ParentNode.InsertAfter(sdtForTextInsert, sdt) and I just get an error about “inserting at this location”

Thank you for any help.
Regards,
Mark

@markchequer Your code is correct, but you should also make sure the newly created SDT is on the same markup level as the reference SDT. For example see the following code:

Document doc = new Document("C:\\Temp\\in.docx");

// Get some SDT.
StructuredDocumentTag sdt = (StructuredDocumentTag)doc.GetChild(NodeType.StructuredDocumentTag, 0, true);

// Create new SDT on the same markup level.
StructuredDocumentTag newSdt = new StructuredDocumentTag(doc, SdtType.RichText, sdt.Level);

// Insert the newly created SDT after the existing SDT.
sdt.ParentNode.InsertAfter(newSdt, sdt);

doc.Save(@"C:\Temp\out.docx");

Thank you, got it.

1 Like