Using Both the Strongly Typed Object Model and LINQ to XML in an Open XML Application

The strongly-typed object model (OM) of the Open-Xml-Sdk is comprised of classes that you use to manipulate the markup within parts. These are classes such as DocumentFormat.OpenXml.Wordprocessing.Paragraph, DocumentFormat.OpenXml.Wordprocessing.Run, and DocumentFormat.OpenXml.Wordprocessing.Text – there are hundreds of such classes in the Open-Xml-Sdk, and these classes are known as the strongly-typed OM.

Sometimes developers want to use the strongly-typed OM of the Open XML SDK in combination with code written using LINQ to XML.  You may want to use functionality from PowerTools for Open XML (which is written using LINQ to XML), and you may want to write your code using the strongly typed OM.  There are variations between the two approaches in how you get and set the contents of parts.

Note – This post previously recommended an approach where you could use LINQ to XML and the strongly-typed OM on an opened document. I no longer recommend this approach. Instead, you should close and reopen the document whenever you need to switch between the strongly-typed OM and LINQ to XML. Given that Open-Xml-PowerTools are written using LINQ to XML, this means that if you are using Open-Xml-PowerTools in combination with the strongly-typed OM, you need to follow the recommendations in this post, which is:

Recommendation:

Close and re-open the Open XML file when switching between using the strongly-typed OM and Open-Xml-PowerTools (written using LINQ to XML).

It would be possible to create a new version of the Open-Xml-Sdk which plays nicely with LINQ to XML, however, at the current moment, these plans are not on the table.

Download – Example Code