Specify XML path in dom4j

I want to parse a large XML file using dom4j. I use the dom4j function so that you can register event handlers for path expressions to ignore elements that I don't need. This function is explained here: http://dom4j.sourceforge.net/dom4j-1.6.1/faq.html#large-doc .

I quote from there: β€œThese handlers will be called at the beginning and at the end of each path registered for a particular handler. When the start tag of the path is found, the onStart method of the handler registered on the path is called. When the end tag of the path is found, the onEnd method of the handler is called, registered along the way.

The onStart and onEnd methods pass an instance of ElementPath, which can be used to retrieve the current element for the given path. If the handler wants to "trim" the constructed tree in order to save memory usage, it can simply call the detach () method of the current element processed by the onEnd () handlers. "

My problem is that I do not know which path I should provide so that all children of the root node are handled using two methods.

My xml file looks something like this:

<root .....>
  <chef name="" ..../>
  <chef name="" ..../>
  <recipe name = .... />
  <recipe name...../>
  ....

If I would like to handle chef items than the path / root / chef. For recipe items, the path will be / root / recipe.

But what is the way that dom4j should be set so that it processes (in onStart (), onEnd ()) both the chef and the recipe items?

Thank you so much!

+3
source
2

addHandler() setDefaultHandler() :

SAXReader reader = new SAXReader();
reader.setDefaultHandler(
new ElementHandler() {
    public void onStart(ElementPath path) {
        // If needed, similar to onEnd, but don't detach.    
    }
    public void onEnd(ElementPath path) {
        Element parent = path.getCurrent().getParent();
        if(parent != null && "/root".equals(parent.getPath()) {
            // Do whatever
        }

        path.getCurrent().detach();
    }
}
);
+2

//root/child:: * //root/descendant:: * , .

. w3schools xpath

+1

Source: https://habr.com/ru/post/1789045/


All Articles