class XmlUtil {

    public static String readUntilEndElementWithDepth(String endElementName, XMLStreamReader reader, XmlEventHandlerWithDepth eventHandler) throws XMLStreamException {
        Objects.requireNonNull(endElementName);
        Objects.requireNonNull(reader);

        String text = null;
        int event;
        int depth = 0;
        while (!((event = reader.next()) == XMLStreamConstants.END_ELEMENT
                && reader.getLocalName().equals(endElementName))) {
            text = null;
            switch (event) {
                case XMLStreamConstants.START_ELEMENT:
                    if (eventHandler != null) {
                        String startLocalName = reader.getLocalName();
                        eventHandler.onStartElement(depth);
                        // if handler has already consumed end element we must decrease the depth
                        if (reader.getEventType() == XMLStreamConstants.END_ELEMENT && reader.getLocalName().equals(startLocalName)) {
                            depth--;
                        }
                    }
                    depth++;
                    break;

                case XMLStreamConstants.END_ELEMENT:
                    depth--;
                    break;

                case XMLStreamConstants.CHARACTERS:
                    text = reader.getText();
                    break;

                default:
                    break;
            }
        }
        return text;
    }

    private  XmlUtil();

}