Capturing XML and Inserting XML in a Word Document

In almost any solution you build in Word, there will be times that you either want to capture the content from part of the document, or insert some additional content at some location in the document. One example scenario I've seen for this are clause libraries where folks want to store a collection of document fragments that can be dynamically inserted into a new document based on what the user is writing about.

In Word, it's easy to both store these fragments as well as insert them into new documents. I already talked a bit about how the cfChunk element makes it easy to insert these fragments if you want to do it on a server (or anywhere that the Word OM isn't available). If you do have your solution running in Word though and have access to the OM, you can use the .xml property and .insertXML method off the range object.


Take any document and open it up in Word 2003. Make a selection that you want to store, and then bring up VBE (Alt + F11). Go to the immediate window (Ctrl + G) and type msgbox selection.range.xml and press return. The message box can't display the whole output, but you can see that you are returned a string that represents the selection you made in the WordprocessingML format. You can take this string and store it off as it's own XML document if you want to store it and re-use it in other documents. You can also load it into an XML DOM and make modifications to it, then reinsert it into the document. The way you insert the XML is through the .insertXML method:


Take the same document and place your cursor somewhere that you want to insert some rich text. Go back into the immediate window in VBE, and type selection.Range.InsertXML ("<foo>My text</foo>") and press return. You can see that your text (and the XML tag <foo>) have been inserted in your document where your cursor was. If you don't see the <foo> tag, just press CTRL + Shift + X to turn the XML tag view on.

In this example we inserted some data-only XML. You can also insert WordprocessingML if you want to apply formatting. With the insertXML method you can insert as much rich content as you want. It could be an entire other document if that's what you wanted to insert. This method gives you the ability to allow the users of your solutions to quickly build up a document from preexisting content.