Invalid Operation - Stack Empty error after removing nodes

I am trying to perform some very basic operations with the DOM. In this case, I’m simply trying to remove all the { MERGEFIELD reference } fields that I find in a document (as a prelude to mail merge). I can’t get to first base. I get an ‘Invalid Operation - Stack Empty’ when I try to save the modified document. All I’m doing is the ‘node.Remove()’ operation on the start node, the end node and every node in between when I find a ‘MERGEFIELD’. Please find, attached, the code.

Hi

Thanks for your request. I suppose you use the following code to remove mergefield:

///
/// Replaces the merge field with the evaluated text.
///
public void Replace()
{
    // Delete the Merge Field from the document.
    Node node = this.StartNode;
    while (node != this.EndNode)
    {
        Node nextNode = node.NextSibling;
        node.Remove();
        node = nextNode;
    }
}

In this code you remove all nodes of the field except FieldEnd. Maybe that is why the problem occurs.
Why don’t you use the built-in method to remove mergefields from the document? In addition, why don’t you use standard Mail Merge functionality of Aspose.Words? If you need just remove line break after your mergefield (if there is no value), then I think it is easier to use MergeField event handler to achieve this.
Best regards.