Quote:The headers and footers aren't in the MainDocumentPart.Document, they are subparts in the 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[^] property instead of Document as a starting point to get the 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()); } } }
doc = WordprocessingDocument.Open(_stream, true); FooterPart footerPart = doc.MainDocumentPart.FooterParts.LastOrDefault(); footerPart.Footer.AppendChild(new Paragraph(new Run(new Text("CUI\n"))));
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)