I've created a template in word. In the template I use content controls for text replacements.
My goal is to have a function with a parameter of IList<string>
. For each entry in that list I want to copy the paragraph. After the replacement it should look like that:
My current code:
static void ReplaceContentControlValueList(WordprocessingDocument doc, string tag, IList<string> values)
{
var contentControl = doc.MainDocumentPart
.GetXDocument()
.Descendants(W.sdt)
.Where(e => e.Elements(W.sdtPr)
.Elements(W.alias)
.Attributes(W.val)
.FirstOrDefault(f => f.Value == tag) != null);
if (contentControl is null)
{
return;
}
var content = contentControl.Descendants(W.sdtContent).First().Descendants(W.p);
var templateParagraph = content.First();
templateParagraph.Remove();
foreach (var value in values)
{
var newElement = new XElement(templateParagraph);
contentControl.Descendants(W.sdtContent).First().Add(newElement);
newElement.Descendants(W.t).FirstOrDefault(f => f.Value == $"{{{tag}}}").Value = value;
}
}
I don't believe that this is the best approach for doing that. Firstly I need to remove the paragraph and secondly all the paragraphs have the same paraId and textId.
How can I do that properly?
question from:
https://stackoverflow.com/questions/65926076/clone-paragraph-within-content-control-with-openxml 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…