We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Find all Mail Merge Fields that are Nested inside IF Fields in Word DOCX Document using C# .NET

I am looking to traverse all the fields on a document and list out the merge fields that are used in an IF statement. Let’s say I have a document with this merge field:

{ IF {MERGEFIELD firstname} = “John” “Billy” “{ IF {MERGEFIELD lastname} = “Pipe” “Fuller” “Baker”}”}

I want pull out the value “firstname” and “lastname”. I have some of the code, but I’m not sure where to go from here. Can you please help point me in the correct direction to pull out the MergeFields that are used in every IF statement in the document?

Aspose.Words.Document doc = new Aspose.Words.Document(wordDoc.FullName);

NodeCollection fieldStarts = doc.GetChildNodes(NodeType.FieldStart, true);

foreach (FieldStart fieldStart in fieldStarts)

if (fieldStart.FieldType.Equals(FieldType.FieldIf))
    Run fieldCode = (Run)fieldStart.NextSibling;



Please see this sample Word DOCX document (Nested Merge Fields inside IF Fields.zip (9.5 KB)) containing the nested Merge Fields inside IF Fields and try running the following C# code of Aspose.Words for .NET API:

Document doc = new Document(@"C:\temp\Nested Merge Fields inside IF Fields.docx");
// Get the target IF field from Word document
FieldIf fieldIf = null;
foreach (Field field in doc.Range.Fields)
    if (field.Type == FieldType.FieldIf)
        fieldIf = (FieldIf)field;

if (fieldIf != null)
    ArrayList list_of_merge_field_names = new ArrayList();

    Node currentNode = fieldIf.Start;
    while (currentNode != fieldIf.End)
        Node nextNode = currentNode.NextPreOrder(currentNode.Document);

        if (nextNode.NodeType == NodeType.FieldStart && ((FieldStart)nextNode).FieldType == FieldType.FieldMergeField)
            FieldMergeField fieldMergeField = (FieldMergeField)((FieldStart)nextNode).GetField();

            if (!list_of_merge_field_names.Contains(fieldMergeField.FieldName))

        currentNode = nextNode;

    foreach (string merge_field_name in list_of_merge_field_names)

That worked great. Thank you so much!