Free Support Forum - aspose.com

Field.Unlink throws java.lang.IllegalStateException

Dear Aspose
We’re using Aspose.Words for Java for merging fields in word documents.Currently we are using Aspose 18.7. In the result document we want the fields unlinked therefore we’re calling unlinkFields() on Document. But for one document this operation raises excepction -

Exception in thread "main" java.lang.RuntimeException: java.lang.IllegalStateException: Document structure was changed.
at com.aspose.words.FieldCollection$zzZ.hasNext(Unknown Source).

Here is snippet, that causes issues

doc.getMailMerge().execute(new String[0], new Object[0]);
doc.updateFields();

for(Field field : doc.getRange().getFields()) {
     if (field.getType() == FieldType.FIELD_MERGE_FIELD || field.getType() == FieldType.FIELD_IF) {
         field.unlink();
    }
}

Is this expected behavior? I have not found topic or document that mentioned this code as antipattern. Unfortunately I cant share that document.

For me it looks similiar to concurrent modification while traversing a collection

@mdygas1

Have you tried the latest version of Aspose.Words for Java 20.5? If you still face problem, please attach the following resources here for testing:

  • Your input Word document.
  • Please create a simple Java application ( source code without compilation errors ) that helps us to reproduce your problem on our end and attach it here for testing.

As soon as you get these pieces of information ready, we will start investigation into your issue and provide you more information. Thanks for your cooperation.

PS: To attach these resources, please zip and upload them.

Hello, @tahir.manzoor. Here is sample program. Thanks for Your time :slight_smile: Also this issue is still in 20.5 version.

aspose.zip (65.1 KB)

@mdygas1

We have tested the scenario and have managed to reproduce the same issue at our side. For the sake of correction, we have logged this problem in our issue tracking system as WORDSNET-20463 . You will be notified via this forum thread once this issue is resolved.

We apologize for your inconvenience.

@tahir.manzoor

HI, I found a partial workaround. Here is it sample:

        for(Section section : doc.getSections()) {
        section.getBody().getRange().unlinkFields();
    }

But this solution has one corner case - If document does not contain sections, what else could I do? Could You give me any advice

@mdygas1

It is nice to hear from you that your problem has been solved. Please note that in Microsoft Word, a valid document needs to have at least one section. Your code example does not unlink the fields in header and footer of document. It only unlink the fields in the body of document.