Getting java.lang.IllegalArgumentException 'This node is not a parent of the oldChild node' while making a visitor that removes bookmarks

Hello,

In our application, we cannot remove bookmarks from Word documents, before saving them in HTML.

We have created a small Java main application that reproduces this issue with Aspose.Words for Java 24.11.
The code and the Word file are included in the attached archive.
aspose-support-remove-bookmarks.zip (1,4 Mo)

void main() throws Exception {
    var doc = new Document("00425195.DOC");
    doc.accept(new RemoveBookmarks());
}

private static class RemoveBookmarks extends DocumentVisitor {
   @Override
   public int visitParagraphStart(Paragraph paragraph) {
      removeNodesOfType(paragraph, NodeType.BOOKMARK_START);
      removeNodesOfType(paragraph, NodeType.BOOKMARK_END);

      return VisitorAction.CONTINUE;
   }

   private void removeNodesOfType(Paragraph paragraph, int nodeType) {
      NodeCollection<Node> bookmarkStartNodes = paragraph.getChildNodes(nodeType, false);

      Iterator<Node> iterator = bookmarkStartNodes.iterator();
      if (iterator.hasNext()) {
         Node next = iterator.next();
         paragraph.removeChild(next);
      }

   }
}

The error is:

Exception in thread “main” java.lang.IllegalArgumentException: This node is not a parent of the oldChild node.
at com.aspose.words.CompositeNode.zzZn1(Unknown Source)
at com.aspose.words.CompositeNode.removeChild(Unknown Source)
at RemoveBookmarks$RemoveBookmarks.removeNodesOfType(RemoveBookmarks.java:23)
at RemoveBookmarks$RemoveBookmarks.visitParagraphStart(RemoveBookmarks.java:11)
at com.aspose.words.Paragraph.acceptStart(Unknown Source)
at com.aspose.words.CompositeNode.acceptCore(Unknown Source)
at com.aspose.words.Paragraph.accept(Unknown Source)
at com.aspose.words.CompositeNode.acceptChildren(Unknown Source)
at com.aspose.words.CompositeNode.acceptCore(Unknown Source)
at com.aspose.words.Body.accept(Unknown Source)
at com.aspose.words.CompositeNode.acceptChildren(Unknown Source)
at com.aspose.words.CompositeNode.acceptCore(Unknown Source)
at com.aspose.words.Section.accept(Unknown Source)
at com.aspose.words.CompositeNode.acceptChildren(Unknown Source)
at com.aspose.words.CompositeNode.acceptCore(Unknown Source)
at com.aspose.words.Document.accept(Unknown Source)
at RemoveBookmarks.main(RemoveBookmarks.java:5)

Thanks in advance for your help.

@nicolaskosinski As I can see you code simply removes bookmarks from the document. Why don’t you use the following code to achieve this:

Document doc = new Document("C:\\Temp\\in.doc");
doc.getRange().getBookmarks().clear();
doc.save("C:\\temp\\out.doc");

If you need to use visitor, then please use the following code:

next.remove();

instead of

paragraph.removeChild(next);