Replace content between bookmark start and end

I have content (images, tables, paragraphs) between a bookmark start and end.

I want to “delete” all of the content in this bookmark and replace it with new content via document builder. The new content could be images, tables, paragraphs, or a mixture of all three.

I want to keep the bookmark as well.

Can anyone help me out, I’m going crazy with something I thought would be simple!

Cheers

Hi Dean,

Thanks for your inquiry. Please use the following code example to achieve your requirements. If you still face problem, please attach your input Word document here for testing. I will investigate the issue on my side and provide you more information.

Document doc = new Document(MyDir + "in.docx");
doc.Range.Bookmarks["bookmark"].Text = "";
doc.Save(MyDir + "Out.docx");

Hi Tahir

I’ve attached a sample Word doc.

I want to move to bookmark2, delete all of the content, the image and table, and then add new content into bookmark2 using document builder.

Cheers ~ Dean

Hi Dean,

Thanks for your inquiry.
Please use the following code example to achieve your requirements. Hope this helps you. Please let us know if you have any more queries.

Document doc = new Document(MyDir + "in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
Node node = (Node)doc.Range.Bookmarks["bookmark2"].BookmarkEnd.NextPreOrder(doc);
if (node != null && node.NodeType == NodeType.Run)
{
    builder.MoveTo(node);
    builder.Writeln();
}
doc.Range.Bookmarks["bookmark2"].Text = "";
builder.MoveToBookmark("bookmark2");
builder.Writeln("Some Text");
builder.InsertImage(MyDir + "in.jpg");
doc.Save(MyDir + "Out.docx");

Hi Tahir

Thanks for the answer, simple when you know how

What does this piece of code do?

Node node = (Node)doc.Range.Bookmarks["bookmark2"].BookmarkEnd.NextPreOrder(doc);

if (node != null && node.NodeType == NodeType.Run)
{
    builder.MoveTo(node);
    builder.Writeln();
}

Hi Dean,

Please accept my apologies for your inconvenience. See the comments in following code snippet. Note that bookmark is a “facade” object that encapsulates two nodes BookmarkStart and BookmarkEnd in a document tree and allows to work with a bookmark as a single object.

// Node.NextPreOrder method gets next node according to the pre-order tree traversal algorithm.
//Get the next pre-order of bookmark end node
Node node = (Node)doc.Range.Bookmarks["bookmark2"].BookmarkEnd.NextPreOrder(doc);
//If node type is Run node insert the paragraph break
//This paragraph break preserve formatting of '3 HEADING THREE'
if (node != null && node.NodeType == NodeType.Run)
{
    builder.MoveTo(node);
    builder.Writeln();
}

Please let us know if you have any more queries.