Reputation: 51
I am trying to programmatically replace text at a bookmark in a Word document. I can find the text at the bookmark (I am using a test document with only one bookmark), and print it out to debug - but can't seem to set the value of the text. How do I replace the text at the bookmark?
WordprocessingDocument wordprocessingDocument=WordprocessingDocument.Open(filepath, true);
foreach (BookmarkStart bookmark in wordprocessingDocument.MainDocumentPart.Document.Body.Descendants<BookmarkStart>())
{
System.Diagnostics.Debug.WriteLine(bookmark.Name + " - " + bookmark.Parent.InnerText);
/* Below line does not work */
bookmark.Parent.InnerText = "My Replacement Text"
}
Upvotes: 4
Views: 1631
Reputation: 2639
Get all bookmark start
public List<WP.BookmarkStart> GetAllBookmarks ()
{
var bmk = _workspace.MainDocumentPart.RootElement.Descendants<WP.BookmarkStart>().ToList();
return bmk;
}
Iterate through all bookmarks
foreach (var bookmark in bookmarks)
{
string modifiedString = GetModifiedString();
ReplaceBookmarkText(bookmark, modifiedString);
}
Replace Bookmark Text
public void ReplaceBookmarkText(WP.BookmarkStart bookmark, string newText)
{
try
{
var bmkText = bookmark.NextSibling<WP.Run>();
if (bmkText != null)
{
bmkText.GetFirstChild<WP.Text>().Text = newText;
wordprocessingDocument.MainDocumentPart.Document.Save();
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
throw;
}
}
Where WP
is
using WP = DocumentFormat.OpenXml.Wordprocessing;
Upvotes: 1