How can i delete a bookmark using docx4j?

1k views Asked by At

Strange thing. I'm trying to delete a "_GoBack" bookmark in a docx file, because it's ruining VariablePrepare (interesting, but different topic). I have a very simple template, and there is only one bookmark, which is:

<w:bookmarkStart w:id="0" w:name="_GoBack"/>
<w:bookmarkEnd w:id="0"/>

It appears anytime i make a change in the template, in the place of the last change.

This code:

MainDocumentPart main = docx.getMainDocumentPart();
List<Object> bmList = getAllElementFromObject(main, CTBookmark.class);
CTBookmark bm = (CTBookmark) bmList.get(0);
System.out.println(bm.getName());

gives me "_GoBack", so i'm sure that the bookmark is found correctly. But strangely if i do this:

getAllElementFromObject(main, CTBookmark.class).remove(0);

the bookmark doesn't get deleted. To check, this code:

System.out.println(getAllElementFromObject(main, CTBookmark.class).size());
getAllElementFromObject(main, CTBookmark.class).remove(0);
System.out.println(getAllElementFromObject(main, CTBookmark.class).size());

returns

1
1

Should i use some other approach to delete a bookmark in docx4j?

1

There are 1 answers

3
JasonPlutext On BEST ANSWER

You don't provide the code for your method getAllElementFromObject, but I guess it doesn't find a CTBookmark object which is wrapped in a JAXB element.

From the BookmarksDeleter.java sample:

    // Can't just remove the object from the parent,
    // since in the parent, it may be wrapped in a JAXBElement
    for (Object ox : theList) {
    if (XmlUtils.unwrap(ox).equals(bm)) {
        return theList.remove(ox);
    }

You also need to handle CTMarkupRange?

So yeah, to delete bookmarks using docx4j, see the linked sample, or try RangeFinder.java