[jdom-interest] Protected methods to make private

Bradley S. Huffman hip at csa.cs.okstate.edu
Thu Jun 26 08:52:14 PDT 2003


Laurent Bihanic writes:

> Bradley S. Huffman wrote:
> > Is there some reason we cann't get rid of JDOMResult.FragmentHandler and
> > put the methods getResult and clearResult in SAXHandler?
> 
> SAXHandler was not designed to cope this document fragments. Mixing SAXHandle
> r 
> with document fragment supports leads to ugly code (like using a dummy root 
> element).
> Thus, I don't think it's a good idea to merge FragmentHandler's code unless 
> there's a real need to generalize document fragment support.

I don't think the following is any uglier than "if (atRoot) ..." that's 
currently in comment(), startElement(), processingInstruction(). And SAXHandler
now becomes reuseable, and JDOMResult becomes simpler :)

    private Parent parent = null;
    private List result = new ArrayList();

    // Return document, or null if results weren't a well-formed document.
    public Document getDocument() {
        Document document = null;
        if (parent instanceof Document) {
            document = (Document) parent;
        }
        return document;
    }

    // Return current or final results of SAX events as a List. If results
    // where a well-formed document then getResult().get(0) will contain
    // the document.
    public List getResult() {
        return result;
    }

    // Clear all results and reset SAXHandler for reuse
    public void clearResult() {
        parent == null;
        result.clear();
        textBuffer.clear();
    }

    public startDocument() {}

    public endDocument() {
        parent = factory.document(result); // If document(List) is a constructor
        result.clear();
        result.add(parent);
    }

At end of startElement()

    if (parent == null) {
        result.add(element);
    }
    else {
        parent.addContent(element);
    }
    parent = element;

At end of endElement()

    parent = ((Element) parent).getParent();

In comment(), processingInstruction(), flushCharacters(), etc.

    if (parent == null) {
        result.add(...);
    }
    else {
        parent.addContent(...);
    }

Brad



More information about the jdom-interest mailing list