Using Bookmarks to Annotate XML

You can use a cursor to insert bookmarks that annotate XML with markers containing information you design. These bookmarks aren't written into the XML itself, but in a sense "hang" from the location where it was inserted. In this way you can associate arbitrary pieces of information with specific parts of the XML.

You design your own bookmark classes by extending XmlBookmark, a nested class of XmlCursor. You can design your bookmark class to contain information specific to your needs.

In the following example, OrderBookmark is an inner class that extends XmlCursor.XmlBookmark. It merely stores a piece of text.

/*
 * The OrderBookmark class includes a constructor through which you will
 * insert your bookmark's content. It also includes get and set methods
 * you can use to retrieve and change the content.
 */
static class OrderBookmark extends XmlCursor.XmlBookmark {
    public OrderBookmark (String text) { TEXT = text; }
    public String TEXT;
    public String getText() { return TEXT; }
    public void setText(String newText) { TEXT = newText; }
}

You can use instances of this class to store bookmarks at places in your XML. The following excerpt of code creates a cursor and an instance of the OrderBookmark class. Then it uses the cursor to insert the bookmark at the cursor's current location.

    XmlCursor orderCursor = xmlDoc.newCursor();
    OrderBookmark thisBookmark = new OrderBookmark("foo");
    orderCursor.setBookmark(thisAnnotation);

Related Topics

Navigating XML with Cursors