//....
//.... (The same code as in the previous case is omitted.)
//Get bookmark content
BookmarksNavigator navigator = new BookmarksNavigator(doc);
navigator.moveToBookmark("test_bookmark");
TextBodyPart body = navigator.getBookmarkContent();
//Now you can get all objects between the keywords from body.getBodyItems()
//*****************Change******************//
//Delete all objects in the body
body.getBodyItems().clear();
//.....
//TextBodyPart body = navigator.getBookmarkContent();
//body.getBodyItems().clear();
//Replace the current body with an empty one to delete all content between the two marks
TextBodyPart body=new TextBodyPart(document);
navigator.replaceBookmarkContent(body);
//....
Document document = new Document();
document.loadFromFile("PruebaWord2.docx");
TextSelection startSelection = document.findPattern(Pattern.compile("<if-test>",Pattern.CASE_INSENSITIVE));
TextSelection endSelection = document.findPattern(Pattern.compile("<\\/if-test>",Pattern.CASE_INSENSITIVE));
TextRange startRange = startSelection.getAsOneRange();
TextRange endRange = endSelection.getAsOneRange();
Paragraph startPara = startRange.getOwnerParagraph();
Paragraph endPara = endRange.getOwnerParagraph();
int startIndex = startPara.getChildObjects().indexOf(startRange);
int endIndex = endPara.getChildObjects().indexOf(endRange);
//If start and end marks are in a same paragraph, use a loop to remove other objects between them
if(startPara.equals(endPara)){
for(int i=startIndex+1,j=endIndex;i<j;){
startPara.getChildObjects().removeAt(i);
j--;
}
}else{
//Otherwise, use an empty body for replacing
BookmarkStart bookmarkStart = new BookmarkStart(document, "test_bookmark");
BookmarkEnd bookmarkEnd = new BookmarkEnd(document, "test_bookmark");
if (startIndex == startPara.getChildObjects().getCount() - 1) {
startPara.getChildObjects().add(bookmarkStart);
} else {
startPara.getChildObjects().insert(startIndex + 1, bookmarkStart);
}
endPara.getChildObjects().insert(endIndex, bookmarkEnd);
BookmarksNavigator navigator = new BookmarksNavigator(document);
navigator.moveToBookmark("test_bookmark");
//Replace the current body with an empty one to delete all content between the two marks
TextBodyPart body=new TextBodyPart(document);
navigator.replaceBookmarkContent(body);
//Remove the bookmark
startPara.getChildObjects().remove(bookmarkStart);
endPara.getChildObjects().remove(bookmarkEnd);
}
document.saveToFile("PruebaWord-procesado.docx", FileFormat.Docx);