Class XHTMLBalancingHandler

All Implemented Interfaces:
ContentHandler, DTDHandler, EntityResolver, ErrorHandler

public class XHTMLBalancingHandler extends ContentHandlerDecorator
SAX decorator that tracks open elements so a parser can recover well-formed XHTML when an exception interrupts the SAX stream mid-element.

The decorator is a thin passthrough on the happy path: it pushes and pops an internal stack on startElement/endElement and otherwise forwards every event to the wrapped handler unchanged. It deliberately does NOT mask bad event sequences (mismatched or excess endElement, duplicate attributes, etc.) -- those remain visible to StrictXHTMLValidator so parser bugs still surface as test failures.

The unhappy path -- a per-part SAX parser throwing mid-element after emitting one or more start tags -- is handled via drainOpenElements(), which emits a matching endElement (with the original uri/localName/qName) for every element still on the stack, in reverse open order. The wrapped handler is left in a well-formed state with no dangling elements from the failed sub-parse.

Typical use wraps the handler that receives events from an inner SAX parser, inside the catch arm that swallows the inner parser's exception:

XHTMLBalancingHandler balancer = new XHTMLBalancingHandler(contentHandler);
try {
    XMLReaderUtils.parseSAX(stream, new EmbeddedContentHandler(balancer), context);
} catch (SAXException e) {
    balancer.drainOpenElements();
    // ... log and continue ...
}
This handler does not touch startDocument/endDocument; the caller still owns the document lifecycle.