tampsystems
asked on
OpenXML Iterate and Replace
How do you iterate through all the content controls? I have a document with several RichText content controls but the process is not finding all the content controls within the document. It appears that it is only finding content controls that are on the root and not ones that are within the body text.
Also, once I find a content control how do I replace the text?
This should be easy right?
Also, once I find a content control how do I replace the text?
This should be easy right?
public static void MyMethod(string docfile)
{
using (WordprocessingDocument doc = WordprocessingDocument.Open(docfile, true))
{
var docPart = doc.MainDocumentPart;
// Find the first content control whose Alias property matches the supplied name.
var sdts = docPart.Document.Descendants<SdtBlock>();
foreach (var sdt in sdts)
{
//todo it is not finding all content controls, it appeas they can't be with the body text
if (sdt.SdtContentBlock.InnerText == "ReplaceMeText")
{
//todo how to replace text: sdt.SdtContentBlock.InnerText = "MyNewText";
System.Diagnostics.Debug.WriteLine("Found" + sdt.SdtContentBlock.InnerText);
}
}
}
}
ASKER
I tried your code but it appears that all of the SdtAlias were null.
SdtAlias alias = sdt.Descendants<SdtAlias>( ).FirstOrD efault();
if (alias != null) //always null
SdtAlias alias = sdt.Descendants<SdtAlias>(
if (alias != null) //always null
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I found that some of the content controls were of type "StdBlock", but some others were of type "SdtRun".
Best thing to do it is to firstly check out the Open XML SDK Productivity Tool, which opens your document and reflects the code. Then you can drill down to where you know the controls are and see what type of element they are.
I also made myself a little console app that analyses a file and tells me how many blocks and runs there are, and what their control name is. It's real simple. THere's probably much better ways to do this, but I'm new to this too, and it works for me. Here's my analysis program:
Open in new window
Hope this helps.
Cheers,
Tim.