<CharlieDigital/> Programming, Politics, and uhh…pineapples

14Oct/10Off

Getting All Content Controls using OpenXML

If you're trying to get all of the content controls in an OpenXML document, the most obvious way to do it would be:

// Get the document instance
WordprocessingDocument document = ...; 

// Get all of the SdtBlock elements
document.MainDocumentPart.Document.Descendants<SdtBlock>();

But this will only get you some of the content controls.  Basically, it won't return any nested, inline content controls (nested, non-inline content controls are still returned).  Nested, inline content controls are still tagged as <sdt/>, but the corresponding class name is actually SdtRun, not SdtBlock.

To get all of the content controls, you need to use the following code instead:

// Get the document instance
WordprocessingDocument document = ...; 

// Get all of the SdtElement elements
document.MainDocumentPart.Document.Descendants<SdtElement>();

The resultset will include SdtBlock and SdtRun elements.  This had me coding in circles for a few hours....

Note that likewise, the content element is different between the two.  For SdtBlock, the content element is an SdtContentBlock.  For SdtRun, the content element is an SdtContentRun.

Posted by Charles Chen

Filed under: .Net, Office Comments Off
Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

Trackbacks are disabled.