Replace text between two mergefields

I am looking for a way to replace text between two Mergefields. The text will be between the FieldEnd of the start tag and FieldStart of the end tag.
For example:
<<StartTag>> this is default text <<EndTag>>

After mail merge, should show the final result as:
replaced text

I am thinking of using visitFieldStart, visitFieldEnd, moveToMergeField, insertHtml methods of DocumentVisitor. I am wondering if there is another standard approach for this? Right now, I will have to traverse through nodes and remove each to delete the default text and moveToMergeField to insert new text. But I do not wish to traverse and delete nodes myself if there is a straightforward way to do that.
Please let me know if you have any ideas.

Thanks a lot

Hi there,

Thanks for your inquiry. I suggest you please read the following article about ‘Find and Replace Overview’. Hope this helps you.
https://docs.aspose.com/words/java/find-and-replace/

If you want to replace the contents between two mail merge fields, your approach is correct to replace the contents. If you know the text between mail merge fields, you can use find and replace approach shared in above documentation link.

Please let us know if you have any more queries.

Hi !

Thanks for your reply. I ll take a look at Find/Replace.

I do not know what the text is going to be as it will be different for each pair of tags and there can be multiple pairs(StartTag, EndTag) in the whole document. I will have a list of strings with which I will replace content between each pair of tags.

Thanks a lot.

Hi there,

Thanks for your inquiry. In your case, I suggest you following solution.

  1. Replace the text with empty string using Range.replace method. See this documentation link.
  2. Move the cursor to mail merge field
  3. Insert new contents

Please check the following code example for your kind reference. 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);
doc.getRange().replace("this is default text", "", false, true);
builder.moveToMergeField("StartTag", true, false);
builder.writeln("New text");
doc.save(MyDir + "Out.docx");