5
votes

I am beginner to open xml sdk. I am trying to find out all merge fields of document.

But I am not getting the headers and footers merge fields.

Can any one suggest a working solution?

I am trying some thing like this -

foreach (FieldCode field in docGenerated.MainDocumentPart.RootElement.Descendants<FieldCode>())
                    {

                        String fieldText = field.Text;
                        if (fieldText.StartsWith(" MERGEFIELD"))
                        {
                            Int32 endMerge = fieldText.IndexOf("\\");

                            Int32 fieldNameLength = fieldText.Length - endMerge;

                            String fieldName = fieldText.Substring(11, endMerge - 11);

                            fieldName = fieldName.Trim();
                         }
}
1
What are merge fields in a word document?Yair Nevet
Merge field is a type of field in Microsoft Word etc. to create merge or mail merge document.Ramashanker Tripathi

1 Answers

4
votes

You have to loop through header and footer separately, see the following code:

foreach (var header in doc.MainDocumentPart.HeaderParts)
            foreach (var cc in header.RootElement.Descendants<FieldCode>())
                //DO CODE
foreach (var footer in doc.MainDocumentPart.FooterParts)
           foreach (var cc in footer.RootElement.Descendants<FieldCode>())
                //DO CODE