Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

c# - Clone paragraph within content control with openxml

I've created a template in word. In the template I use content controls for text replacements.enter image description here

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:

enter image description here

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...