Replacing Text of Content Controls in OpenXML

白昼怎懂夜的黑 提交于 2019-12-02 04:54:09

问题


I have a word file that have multy Rich Text Content Control I want to change text of it. I Use this code .

 using (WordprocessingDocument theDoc = WordprocessingDocument.Open(docName, true))
 {
    MainDocumentPart mainPart = theDoc.MainDocumentPart;
    foreach (SdtElement sdt in mainPart.Document.Descendants<SdtElement>())
    {
        SdtAlias alias = sdt.Descendants<SdtAlias>().FirstOrDefault();
        if (alias != null)
        {
            string sdtTitle = alias.Val.Value;
            var t = sdt.Descendants<Text>().FirstOrDefault();
            t.Text="Atul works at Microsoft as a .NET consultant. As a consultant his job is to design, develop and deploy";
        }
    }
 }

It is add new text with old text. But i want to replace this!!!


回答1:


You only retrieve and update the first Text of your sdtContent. To replace all of it, the simples way is:

  • Delete all text
  • Add the new text

Update your code with:

if (alias != null)
{
    // delete all paragraph of the sdt
    sdt.Descendants<Paragraph>().ToList().ForEach(p => p.Remove());
    // insert your new text, who is composed of:
    // - A Paragraph
    // - A Run
    // - A Text
    sdt.Append(new Paragraph(new Run(new Text("As a consultant his job is to design, develop and love poney."))));
}

edit: I forget to add the paragraph and the run

You can see how is build a SdtContent here https://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.sdtcontentblock(v=office.14).aspx



来源:https://stackoverflow.com/questions/31750228/replacing-text-of-content-controls-in-openxml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!