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

Free Support Forum - aspose.com

Embedded fields (i.e a field within a field)

Hi,
I’m using doc.Range.Fields to enumerate all fields, and field.GetFieldCode() to convert the field code to a string.
The documents sometimes contain fields with further fields inside them, e.g.:

{ IF { MERGEFIELD InvoiceNumber } <> "" "Invoice No: " "" }

When enumerating the fields, they are treated as two separate fields (once for the IF, and again for the MERGEFIELD). Is there any way to get the entire string at once?

thanks
Kris

Hi Kris,

Thanks for your inquiry. A field in a Word document is a complex structure consisting of multiple nodes that include field start, field code, field separator, field result and field end. Fields can be nested, contain rich content and span multiple paragraphs or sections in a document. The Field class is a “facade” object that provides properties and methods that allow to work with a field as a single object.

The Start, Separator and End properties point to the field start, separator and end nodes of the field respectively.

The content between the field start and separator is the field code. The content between the field separator and field end is the field result. The field code typically consists of one or more Run objects that specify instructions. The processing application is expected to execute the field code to calculate the field result.

Please use following method to get the field code of nested fields. Hope this helps you. Please let us know if you have any more queries.

private static string GetFieldCode(Aspose.Words.Fields.FieldStart fieldStart)
{
    StringBuilder builder = new StringBuilder();
    fieldStart.GetField().Result = "";
    Node currentNode = fieldStart;
    while (currentNode != fieldStart.GetField().End)
    {
        currentNode = currentNode.NextPreOrder(fieldStart.Document);
        if (currentNode.NodeType == NodeType.FieldStart)
            ((FieldStart)currentNode).GetField().Result = "";
        if (currentNode.NodeType == NodeType.Run)
            builder.Append(currentNode.ToString(SaveFormat.Text));
    }
    return builder.ToString();
}

Hi Tahir, thanks very much for your response - this makes complete sense and works well.
Thanks,
Kris