5

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();
                         }
}
Mr Smith
  • 3,318
  • 9
  • 47
  • 85

1 Answers1

4

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
st mnmn
  • 3,555
  • 3
  • 25
  • 32