Retrieving A List of SdtBlocks for A Tag Value Using LINQ

by

If you are using a template document and replacing text programmatically using the Office Open XML SDK 2 API you will need a way to identify the target to be replaced.  One option is to use a Content Control and setting the tag value the same for all of the controls that need to be substituted with a single value.  After some trial and error and a lot of digging through the DocumentReflector I came up with the following LINQ query to get a list of all blocks with the same tag name.

var blocks = from s in part.MainDocumentPart.Document.Descendants<SdtBlock>()
              where (
                      s.GetFirstChild<SdtProperties>().GetFirstChild<Tag>() != null
                     && s.GetFirstChild<SdtProperties>().GetFirstChild<Tag>().Val.Value.Equals(placeholder)
                      )
              select s;

 

 

The nice thing is that all Word document content controls have the tag property as an option so this works whether you are searching for text, rich text or quick parts.  If you are searching for images and some other content controls you may have to search for SdtRuns instead of SdtBlocks, but the query is essentially the same.

del.icio.us Tags: ,,,

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: