Agile Tortoise

Greg Pierce’s blog

« My year in music, 2006      Baby name wizard »

Interesting Microsoft Word XMLNode selection behavior

Since I have not yet passed out from beating my head against the wall, I’d thought I’d report an interesting finding regarding the Microsoft Word object model. The object model includes methods to access content based on embedded XML, but you don’t really get a DOM to manipulate those nodes so you have to rely on selections/ranges and cut/paste operations to move around the data.

It’s a little tricky to figure out exactly how it’s going to treat the XMLNode object ranges, however. For example, the XMLNode has a “Cut” method that selects the node and cuts it to the clipboard — including the surrounding XML element. The XMLNode also has a “Range” property to determine Start/End points, or select content of the node. The area of the “Range” on a node does not include the node XML element, however. So the results of the code lines below are not the same:

node.Cut(); // entire node w/ element tag in clipboard

app.Selection.SetRange( node.Range.Start, node.Range.End );
app.Selection.Cut(); // xml element tag still in document and not in clipboard

As if this is odd enough, the XML element tags are treated differently depending on whether they are currently displayed in the View ( the “Show XML Tags” checkbox on the XML structure Action Pane in Office 2003 or greater ). So you need to write your code to test for whether they are displayed or not before you start to move things around and determine your selection offsets appropriately.

The documents that I’m generating for this application using the new OpenXml formats are easy to create and manipulate — but I’m still stuck having to work inside the Word application via an Add-In to provide some user tools to alter the documents, and it’s painful to say the least. Ah, just to get back to some plain old HTML!

Friday, January 5th, 2007 at 9:30 am and is filed under .NET, C#, OpenXML. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply