Get Text within a Bookmark in C#, VB.NET

Spire.Doc supports to retrieve, replace and delete bookmark content of a specified bookmark. This article will show you how we can get the plain text within a bookmark by using Spire.Doc with C# and VB.NET.

Step 1: Create a Document instance, and load a sample Word document.

Document doc = new Document();
doc.LoadFromFile("Bookmark.docx");

Step 2: Creates a BookmarkNavigator instance to access the bookmark.

BookmarksNavigator navigator = new BookmarksNavigator(doc);

Step 3: Locate a specific bookmark by bookmark name. Call the method GetBookmarkContent to get content within the bookmark.

navigator.MoveToBookmark("bookmark_1");
TextBodyPart textBodyPart = navigator.GetBookmarkContent();

Step 4: Iterate through the items in the bookmark content to get the plain, unformatted text of the bookmark.

string text = null;
foreach (var item in textBodyPart.BodyItems)
{
    if (item is Paragraph)
    {
        foreach (var childObject in (item as Paragraph).ChildObjects)
        {
            if (childObject is TextRange)
            {
                text += (childObject as TextRange).Text;
            }
        }
    }
}

Result:

Get Text within a Bookmark in C#, VB.NET

Full Code:

[C#]
Document doc = new Document();
doc.LoadFromFile("Bookmark.docx");

BookmarksNavigator navigator = new BookmarksNavigator(doc);
navigator.MoveToBookmark("bookmark_1");
TextBodyPart textBodyPart = navigator.GetBookmarkContent();

string text = null;
foreach (var item in textBodyPart.BodyItems)
{
    if (item is Paragraph)
    {
        foreach (var childObject in (item as Paragraph).ChildObjects)
        {
            if (childObject is TextRange)
            {
                text += (childObject as TextRange).Text;
            }
        }
    }
}
Console.WriteLine(text);
[VB.NET]
Document doc = New Document()
doc.LoadFromFile("Bookmark.docx")
 
Dim navigator As BookmarksNavigator = New BookmarksNavigator(doc)
navigator.MoveToBookmark("bookmark_1")
Dim textBodyPart As TextBodyPart = navigator.GetBookmarkContent()


Dim text As String = Nothing
Dim item As var
For Each item In textBodyPart.BodyItems
    If TypeOf item Is Paragraph Then
        Dim childObject As var
        For Each childObject in(item as Paragraph).ChildObjects
            If TypeOf childObject Is TextRange Then
                text += (childObject as TextRange).Text
            End If
        Next
    End If
Next
Console.WriteLine(text)