In my case I had a Microsoft Office Word document which contains content place controls which needs to be filled by specific data after specific business action.
The idea is to select all the descendants from type “SdtElement” which has a tag name specified and then compare it with the provided tag name.
Next, remove all the text from the content control and add our new value.
Sample code:
private void ModifyDocumentPlaceHolder(Document document, string tagName, string value)
{
// Find all placeholders with Tag name
var placeHolders = document.MainDocumentPart.RootElement.
Descendants<SdtElement>().
Where(P => P.Elements<SdtProperties>().FirstOrDefault().
Elements<Tag>().FirstOrDefault() != null);
// Select the required element by tag name
var requiredPlaceHolder = placeHolders.FirstOrDefault(P =>
P.Elements<SdtProperties>().FirstOrDefault().
Elements<Tag>().FirstOrDefault().Val == tagName);
// Remove all text from the place holder
requiredPlaceHolder.Descendants<Text>().ToList().ForEach(
delegate(Text textObj)
{
textObj.Text = string.Empty;
});
// Add the required text
requiredPlaceHolder.Descendants<Text>().FirstOrDefault().Text = value;
}
I hope that helped
Ahmed