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:
1 2 3 4 5 |
// 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:
1 2 3 4 5 |
// 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.