Search code examples
c#ms-wordopenxmlbookmarks

Reading Word Bookmarks using Open XML and C#


I have read everything I can find that is even remotely related to this (including Read Word bookmarks), but have not been able to get anything to work.

I am trying to walk through a Word document that has bookmarks in it, and get the values for each of the bookmarks. I can walk the document and get the names of the bookmarks, but cannot figure out how to get the value/text of the bookmark.

Here is what I am using to get the bookmark names:

using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(athleteFile, false))
{
    foreach (BookmarkStart bookmark in wordDocument.MainDocumentPart.Document.Body.Descendants<BookmarkStart>())
    {       
        System.Diagnostics.Debug.WriteLine(bookmark.Name + " - " + bookmark.InnerText);
    }
}

Solution

  • First of all I'd highly recommend you use the Open XML SDK 2.5 Productivity tool, that way you'll have a better idea of what you're working with.

    Secondly a bookmark in Word does not have any value associated with it. It is usually marks a location in the word document. So what you're trying to do wont work.

    <w:bookmarkStart w:name="bkStart" w:id="0" />
    

    that is the XML element that is created in the docx file when you add a bookmark to the document.