替换 OpenXML 中内容控件的文本

Replacing Text of Content Controls in OpenXML

我有一个包含多个 Rich Text Content Control 的 word 文件,我想更改其中的文本。我使用此代码。

 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";
        }
    }
 }

是旧文加新文。但是我想要replace这个!!!

您只检索和更新 sdtContent 的第一个文本。 要全部替换,最简单的方法是:

  • 删除所有文本
  • 添加新文本

更新您的代码:

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."))));
}

编辑: 我忘记添加段落和 运行

您可以在此处查看如何构建 SdtContent https://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.sdtcontentblock(v=office.14).aspx