Inserting text after a bookmark in openxml

John Baum picture John Baum · Mar 19, 2012 · Viewed 9.5k times · Source

I am looking for a way to insert some text after a bookmark in a word doc using openxml. So far, i have been able to locate the bookmark using the following:

var bookmarks = mainPart.Document.Descendants<BookmarkStart>().ToList();
var bookMarkToWriteAfter = bookmarks.FirstOrDefault(bm => bm.Name == insertAfterBoomark.Name);

This bookmark in the word doc is a selection of two lines in the doc. I have to insert some text right after the two line selection. I have tried to insert text using the following:

var run = new Run();
run.Append(new Text("Hello World"));
bookMarkToWriteAfter .Parent.InsertAfterSelf(run);

mainPart.Document.Save();

This however does not produce the desired result. Does anyone know of the correct way to insert text right after a bookmark in a word doc using openxml?

Answer

Flowerking picture Flowerking · Mar 19, 2012

using

bookMarkToWriteAfter.Parent.InsertAfterSelf(run);

you are trying to work with XML directly which is not always advisable with OpenXML.

Try This..

    Body body = mainPart.Document.GetFirstChild<Body>();
    var paras = body.Elements<Paragraph>();

    //Iterate through the paragraphs to find the bookmarks inside
    foreach (var para in paras)
    {
        var bookMarkStarts = para.Elements<BookmarkStart>();
        var bookMarkEnds = para.Elements<BookmarkEnd>();


        foreach (BookmarkStart bookMarkStart in bookMarkStarts)
        {
            if (bookMarkStart.Name == bookmarkName)
            {
                //Get the id of the bookmark start to find the bookmark end
                var id = bookMarkStart.Id.Value;
                var bookmarkEnd = bookMarkEnds.Where(i => i.Id.Value == id).First();

                var runElement = new Run(new Text("Hello World!!!"));

                para.InsertAfter(runElement, bookmarkEnd);

            }
        }
   }
   mainPart.Document.Save();