Working with WordprocessingML Paragraphs and Runs (How to Insert a Bookmark)

One of the recurring problems that comes up for Open XML developers is that of doing interesting manipulation of paragraphs and runs.  Too often, however, you need to split runs here and there to insert the markup you want to insert to achieve the goals you want to achieve.  The algorithms to determine which runs to split and where to split them can get too complicated and difficult to debug.  Instead, there is an easier solution – split ALL the runs, and split them ALL into runs of a single character.  Then do your manipulations – insert comments, insert bookmarks, find and replace text, insert content controls.  The list goes on and on.

This video presents a tiny snippet of code that shows how to split runs into multiple runs, each having a single character.  The attached code also contains a method to coalesce the runs back together, so after doing your manipulations, you can put the content back in the normalized form.

The specific example that the code shows is how to insert a bookmark, but this is a more generalized technique that you can use in many scenarios.

Code is attached.

Download – Example Code