Search code examples
c#ms-wordopenxmlopenxml-sdk

Replace bookmark text in Word file using Open XML SDK


I assume v2.0 is better... they have some nice "how to:..." examples but bookmarks don't seem to act as obviously as say a Table... a bookmark is defined by two XML elements BookmarkStart & BookmarkEnd. We have some templates with text in as bookmarks and we simply want to replace bookmarks with some other text... no weird formatting is going on but how do I select/replace bookmark text?


Solution

  • Here's my approach after using you guys as inspiration:

      IDictionary<String, BookmarkStart> bookmarkMap = 
          new Dictionary<String, BookmarkStart>();
    
      foreach (BookmarkStart bookmarkStart in file.MainDocumentPart.RootElement.Descendants<BookmarkStart>())
      {
          bookmarkMap[bookmarkStart.Name] = bookmarkStart;
      }
    
      foreach (BookmarkStart bookmarkStart in bookmarkMap.Values)
      {
          Run bookmarkText = bookmarkStart.NextSibling<Run>();
          if (bookmarkText != null)
          {
              bookmarkText.GetFirstChild<Text>().Text = "blah";
          }
      }