Can I tell what's inside of a bookmark?

I received a document where a bookmark was improperly placed. It spanned a table and many other elements that it was not supposed to span. (I understand that placing bookmarks like this is allowed in Word). I would like to be able to check for this. In our system, bookmarks should enclose text and only text. Is there way to check for this? Can you suggest an approach?

@riwright You can use code like the following to check what types of nodes are between bookmark start and end:

Document doc = new Document("C:\\Temp\\in.docx");

// Get bookmark and loop through the nodes between start and end
Bookmark bk = doc.getRange().getBookmarks().get("test");
Node curNode = bk.getBookmarkStart().nextPreOrder(doc);
while (curNode != null && !curNode.equals(bk.getBookmarkEnd()))
{
    Node nextNode = curNode.nextPreOrder(doc);
    // print node type
    System.out.println(NodeType.toString(curNode.getNodeType()));
    curNode = nextNode;
}

Thanks, that’s very helpful.

1 Like