| Цитата | dom4j provides an event based model for processing XML documents. Using this event based model allows developers to prune the XML tree when parts of the document have been successfully processed avoiding having to keep the entire document in memory.
For example, imagine you need to process a very large XML file that is generated externally by some database process and looks something like the following (where N is a very large number).
<ROWSET> <ROW id="1"> ... </ROW> <ROW id="2"> ... </ROW> ... <ROW id="N"> ... </ROW> </ROWSET> We can process each <ROW> at a time, there is no need to keep all of them in memory at once. dom4j provides a Event Based Mode for this purpose. We can register an event handler for one or more path expressions. These handlers will then be called on the start and end of each path registered against a particular handler. When the start tag of a path is found, the onStart method of the handler registered to the path is called. When the end tag of a path if found, the onEnd method of the handler registered to that path is called.
The onStart and onEnd methods are passed an instance of an ElementPath, which can be used to retrieve the current Element for the given path. If the handler wishes to "prune" the tree being built in order to save memory use, it can simply call the detach() method of the current Element being processed in the handlers onEnd() method.
So to process each <ROW> individually we can do the following.
// enable pruning mode to call me back as each ROW is complete SAXReader reader = new SAXReader(); reader.addHandler( "/ROWSET/ROW", new ElementHandler() { public void onStart(ElementPath path) { // do nothing here... } public void onEnd(ElementPath path) { // process a ROW element Element row = path.getCurrent(); Element rowSet = row.getParent(); Document document = row.getDocument(); ... // prune the tree row.detach(); } } );
Document document = reader.read(url);
// The document will now be complete but all the ROW elements // will have been pruned. // We may want to do some final processing now ...
|
|