[jdom-interest] Simpliyfing Filters

Elliotte Rusty Harold elharo at metalab.unc.edu
Fri May 3 09:04:27 PDT 2002


Simplicity is better. But there might be a use-case for read-only 
snapshots. Or perhaps where you want to allow different sorts of 
things to be added than read. For example, in Document you might want 
to allow the root element to be read but not added because there an 
be only one. Same story for DocType if we add it to the content list 
of Document as has been proposed.

At the very least, it makes writing implementations easier. Here's an 
example I wrote recently:

import org.jdom.filter.Filter;
import org.jdom.*;
import java.util.List;


public class StylesheetFilter implements Filter {

   // This filter is read-only. Nothing can be added or removed.
   public boolean canAdd(Object o) {
     return false;
   }

   public boolean canRemove(Object o) {
     return false; 
   }

   public boolean matches(Object o) {
   
     if (o instanceof ProcessingInstruction) {
       ProcessingInstruction pi = (ProcessingInstruction) o;
       if (pi.getTarget().equals("xml-stylesheet")) {
         // Test to see if we're outside the root element
         if (pi.getParent() == null) {
           Document doc = pi.getDocument();
           Element root = doc.getRootElement();
           List content = doc.getContent();
           if (content.indexOf(pi) < content.indexOf(root)) {
             // In prolog
             return true;
           }
         }
       }
     }
     return false;
   
   }
    
}

On the other hand, if there were no canRemove() and canAdd() in 
Filter, then I wouldn't have to implement them at all which would be 
even easier. Let me think about this one a little more.
-- 

+-----------------------+------------------------+-------------------+
| Elliotte Rusty Harold | elharo at metalab.unc.edu | Writer/Programmer |
+-----------------------+------------------------+-------------------+
|          The XML Bible, 2nd Edition (Hungry Minds, 2001)           |
|             http://www.cafeconleche.org/books/bible2/              |
|   http://www.amazon.com/exec/obidos/ISBN=0764547607/cafeaulaitA/   |
+----------------------------------+---------------------------------+
|  Read Cafe au Lait for Java News:  http://www.cafeaulait.org/      |
|  Read Cafe con Leche for XML News: http://www.cafeconleche.org/    |
+----------------------------------+---------------------------------+



More information about the jdom-interest mailing list