使用 Open XML SDK 更新页眉和页脚中的内容控制文本

Update Content-Control Text in Header and Footer using Open XML SDK

要更改文档正文中的内容控制文本,我正在这样做:

var elements = doc.MainDocumentPart.Document
    .Descendants<SdtElement>()
    .Where(s => s.SdtProperties.ChildElements.Count > 0 && 
                s.SdtProperties.GetFirstChild<Tag>()?.Val == contentControlTag);

foreach (var element in elements)
{
    if (element == null)
    {
        continue;
    }

    var elementText = element.Descendants<Text>();

    if (elementText != null)
    {
        var elementTextValue = elementText.FirstOrDefault();

        if (elementTextValue != null)
        {
            elementTextValue.Text = text;
        }
        elementText.Skip(1).ToList().ForEach(t => t.Remove());
    }
}

遗憾的是,这并没有改变 Header/Footer 部分。

我想检查每个页面的 header/Footer 部分是否有特定的 Content-Control-Tag 并更改其文本,类似于上面的代码。我怎样才能做到这一点?

页眉和页脚不在 MainDocumentPart.Document 中,它们是 HeaderParts and FooterParts collections off the MainDocumentPart. So you'll need to process each part separately. Fortunately, all of the parts share a common base class, OpenXmlPart, so you can put them together into a list and process them in a loop. Since you'll be dealing with the base class, you'll need to use RootElement 属性 中的子部分,而不是 Document 作为获取 Descendants.

所以最终结果看起来像这样:

var partsToUpdate = new List<OpenXmlPart> { doc.MainDocumentPart }
    .Concat(doc.MainDocumentPart.HeaderParts)
    .Concat(doc.MainDocumentPart.FooterParts);

foreach (var part in partsToUpdate)
{
    var elements = part.RootElement
        .Descendants<SdtElement>()
        .Where(s => s.SdtProperties.ChildElements.Count > 0 &&
                    s.SdtProperties.GetFirstChild<Tag>()?.Val == contentControlTag);

    foreach (var element in elements)
    {
        if (element == null)
        {
            continue;
        }

        var elementText = element.Descendants<Text>();

        if (elementText != null)
        {
            var elementTextValue = elementText.FirstOrDefault();

            if (elementTextValue != null)
            {
                elementTextValue.Text = text;
            }
            elementText.Skip(1).ToList().ForEach(t => t.Remove());
        }
    }
}