How to find nodes created by DocumentBuilder

The DocumentBuilder class is useful for adding new paragraphs and for splitting paragraphs in a Word document. However, often, after adding a new paragraph, I need to perform some operations on the paragraph (e.g. to go through the text of the paragraph and add certain formatting to certain characters). Is there a way to find the handle of the paragraph added by DocumentBuilder?

For instance, if I run:

builder.InsertBreak(BreakType.ParagraphBreak);

This will split an existing paragraph, effectively creating a new paragraph node in the document. How can I then get ahold of the new paragraph node so that I can continue with further processing?

Similarly, if I run:
builder.Writeln(“New paragraph”);

How can I get ahold of the paragraph node of this new paragraph added by Document builder?

Hi Avi,

Thanks for your inquiry. Sure, you can implement custom logic over node insertion in the document by using the following code snippet:

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
doc.NodeChangingCallback = new HandleNodeChanging();
builder.Writeln("New paragraph");
doc.Save(@"C:\Temp\out.docx");

public class HandleNodeChanging : INodeChangingCallback
{
    void INodeChangingCallback.NodeInserted(NodeChangingArgs args)
    {
        if (args.Node.NodeType == NodeType.Paragraph)
        {
            // Do something useful here
        }
    }
    void INodeChangingCallback.NodeInserting(NodeChangingArgs args)
    {
    }
    void INodeChangingCallback.NodeRemoved(NodeChangingArgs args)
    {
    }
    void INodeChangingCallback.NodeRemoving(NodeChangingArgs args)
    {
    }
}

I hope, this helps.

Best regards,