Replacing Content Controls in OpenXML

喜欢而已 提交于 2019-12-02 18:27:13

Perhaps this can help you,

private void DeleteSdtBlockAndKeepContent(MainDocumentPart mainDocumentPart, string sdtBlockTag)
    {
        List<SdtBlock> sdtList = mainDocumentPart.Document.Descendants<SdtBlock>().ToList();
        SdtBlock sdtA = null;

        foreach (SdtBlock sdt in sdtList)
        {
            if (sdt.SdtProperties.GetFirstChild<Tag>().Val.Value == sdtBlockTag)
            {
                sdtA = sdt;
                break;
            }
        }


        OpenXmlElement sdtc = sdtA.GetFirstChild<SdtContentBlock>();
        OpenXmlElement parent = sdtA.Parent;

        OpenXmlElementList elements = sdtc.ChildElements;

        var mySdtc = new SdtContentBlock(sdtc.OuterXml);

        foreach (OpenXmlElement elem in elements)
        {

            string text = parent.FirstChild.InnerText;
            parent.Append((OpenXmlElement)elem.Clone());
        }

        sdtA.Remove();
    }

Take a look at using a Field. The mail merge fields are designed for exactly this purpose.

Carl G

I don't understand from your question if you are only interested in a solution that automatically removes the ContentControl/SDT when you modify it using the OpenXML SDK, or whether you want it to disappear after the content is modifed programmatically or by a user.

If the former, I think you'll have to remove it yourself as Bilel suggested. If the latter, you should look at this property: ContentControl.Temporary ("the ContentControl is automatically deleted when the user types in the control, or when the text in the control is changed programmatically. When the ContentControl is automatically deleted from the document, the text in the control remains in the document.")

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