Remove text between two words

Hi,


we are maintaining few start and end tags to delete the in-between text using program logic.
my document looks like below.

Some text…
<text1_start>
paragraph1
<text1_end>

few paragraphs

<text1_start>
paragraph2
<text1_end>

I want to remove the paragrphs between <text1_start> and <text1_end> tags.
In this case paragraph1 and paragraph2.
Please help me to achieve this functionality.

Hi Sandeep,


Thanks for your inquiry. In your case we suggest you following solution:

1) Implement IReplacingCallback interface and use Range.Replace method to find the text “<text1_start>”.
2) In the IReplacingCallback.Replacing, insert the BookmarkStart node of a bookmark e.g. bookmark1 at the position of matched node.
3) Similarly, find the text “<text1_end>” and insert BookmarkEnd node for same bookmark.
4). Use Bookmark.Text to set the bookmark text to empty string to remove the contents of bookmark.

Please refer to the following articles:

Find and Repalce
Use DocumentBuilder to Insert Document Elements

Hi manzoor,


Thank you. The given approach worked for me.

Meanwhile i have implemented some logic to delete the text between start and end tag. I just want to know, any flaws with the below approach.

reading all the paragraphs and deleting the text from start node to end node.

Node startNode=null;
Node EndNode=null;
NodeCollection lstNodes = doc.GetChildNodes(NodeType.Paragraph, true);

foreach (Paragraph para in lstNodes)
{
if (para.GetText().Contains(startTag))
{
startNode = para;
}
else if(para.GetText().Contains(endTag))
{
EndNode = para;
}

if(startNode != null)
{
para.Remove();
}
if(EndNode != null)
{
startNode = null;
EndNode = null;
}
}

Thanks,
Sandeep

Hi Sandeep,


Thanks for your inquiry.

Yes, you can use the shared approach to remove paragraphs between to tags. However, this approach will work only when there are only paragraphs between start and end tags. If you want to use this code, we suggest you please use Node.ToString Method (SaveFormat.Text) method instead of Node.GetText().

Hi Manzoor,


Sure…Thanks for detailed explanation.
Hi Sandeep,

Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.