How to Convert Block Level Bookmarks to Inline Level using .NET

Recently we’ve upgraded from Aspose 13.12 to 20.10. We came across the following issue, which we initially though was a bug. Apparently nodes of type BookmarkEnd are not always a childnode of the containing paragraph, but can exist on the same level as the paragraph. This behavior is does not occur for nodes of type BookmarkStart, which is always a childnode of the paragraph.

I’ve read this topic, which indicates this is by design: Unexpected Bookmarkend nodes found directly under body

I also noted that the suggested LoadOption.AnnotationsAtBlockLevel isn’t supported anymore: Aspose.Words for .NET 20.4 Release Notes

Then given the attatched project Aspose BookMarkEnd.zip (167.5 KB) with 2 documents (based on Aspose 21.1.0) what causes the difference in the level of the BookmarkEnd. Is there a way in (in Word or Aspose) to force block level BookmarkEnds to be inline again?:

Tree of ‘correct’ document (i’ve filtered out the runs etc):

-Aspose.Words.Paragraph
-Aspose.Words.Paragraph
 --Aspose.Words.BookmarkStart
-Aspose.Words.Paragraph
-Aspose.Words.Paragraph
 --Aspose.Words.BookmarkEnd

Tree of ‘incorrect’ document, where all the BookMarkEnds aren’t childs of paragraphs somehow:

-Aspose.Words.Paragraph
-Aspose.Words.Paragraph
-Aspose.Words.Paragraph
 --Aspose.Words.BookmarkStart
-Aspose.Words.Paragraph
 --Aspose.Words.BookmarkStart
-Aspose.Words.Paragraph
-Aspose.Words.Paragraph
-Aspose.Words.BookmarkEnd
-Aspose.Words.Paragraph
-Aspose.Words.BookmarkEnd
-Aspose.Words.Paragraph
-Aspose.Words.Paragraph
 --Aspose.Words.BookmarkStart
-Aspose.Words.Paragraph
-Aspose.Words.Paragraph
-Aspose.Words.BookmarkEnd
-Aspose.Words.Paragraph
-Aspose.Words.Paragraph

@hro_jordy

You are facing the expected behavior of Aspose.Words. Please unzip your Word document and check the w:bookmarkend in document.xml as shown in attached image.
bookmarkend.png (24.0 KB)

The bookmark start and end nodes are at their correct position.

Your can iterate over bookmarks of document, move the cursor to the first child node of paragraph, and insert BookmarkEnd node as shown below. Hope this helps you.

Document doc = new Document(MyDir + "BookMarkEnd Incorrect.docx");

DocumentBuilder builder = new DocumentBuilder(doc);

foreach (var item in doc.Range.Bookmarks)
{
    if (item.BookmarkEnd.ParentNode.NodeType != NodeType.Paragraph
        && item.BookmarkEnd.NextSibling.NodeType == NodeType.Paragraph)
    {
        Paragraph para = (Paragraph)item.BookmarkEnd.NextSibling;

        builder.MoveTo(para.FirstChild);
        item.BookmarkEnd.Remove();
        builder.EndBookmark(item.Name);
    }
}
doc.Save(MyDir + "21.1.docx");