Para remove is deleting the bookmark of the parent para in Aspose word Dot Net

Hi Team,

I am using the following code to delete a paragraph and the save the output. Here a strange behavior is happening with Aspose word when there are two paras under same bulletin point (as seen in Before screenshot) and the output correctly removes the para 2 and it’s bookmark but along with this it also removed the para 1 bookmark as well (After screenshot and Output file), which shouldn’t happen. Kindly take a look at the attachments and the code and let me know if there is something wrong with the input or the code please?

Code:

Document document = new Document(@"Input.docx");
NodeCollection paragraphs = document.GetChildNodes(NodeType.Paragraph, true);
//Delete
foreach (Paragraph p in paragraphs)
{
    string text = p.ToString(SaveFormat.Text).Trim();
    if (text == //check the string of matching para 2)
    {
        p.Remove();
    }
}
document.Save(@"Output.docx");

Before Screenshot:

After Screenshot:

Input File: Input.docx (57.3 KB)

Output File: Output.docx (53.3 KB)

Thanks,
Karthikeyan

@Karthik_Test_account Structure of your document looks like this:

As you can see the bookmark Para1 starts in one paragraph and ends in another, the same as Para2, when you remove one of such paragraph paragraph the bookmark becomes invalid, i.e. consist of only start or end. Such bookmarks are removed on document validation stage before saving the document.

@alexey.noskov - I can understand but confusing part here is I have selected just the para 1 and have given the bookmark 1 and similarly for other paras as well but not sure how the bookmark start and end is showing that way. If I turn on Show bookmarks in the Microsoft word, it is highlighting para 1 and para 2 as separate bookmarks as seen in the screenshot. Not sure what went wrong, do you have any ways to prevent this incorrect bookmarking?

image.png (11.4 KB)

image.png (22.0 KB)

Thanks,
Karthikeyan

@Karthik_Test_account This occurs because whole paragraph, including paragraph break mark, is wrapped with bookmark:

As you can see on the attached screenshot, the first paragraph is wrapped with bookmark including paragraph break mark and in another paragraph only the paragraph’s content is wrapped with bookmark.
In the second case both bookmark start and bookmark end are inside the paragraph:

<w:p w14:paraId="42DA9533" w14:textId="30BCA5B0" w:rsidR="00C26707" w:rsidRDefault="00C26707">
	<w:bookmarkStart w:id="1" w:name="test2"/>
	<w:r>
		<w:t>Another paragraph</w:t>
	</w:r>
	<w:bookmarkEnd w:id="1"/>
</w:p>

In the first case bookmark end is outside the paragraph.

That’s the exact issue. Thanks for suggesting this solution!

1 Like