import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
// a kind of event handler
interface DomListener
{
public String getURI ();
public String getLocalName ();
public void processTree (Element tree) throws SAXException;
}
/**
* Using SAX to Stream DOM Subtrees
*/
public class DomFilter extends DefaultHandler
{
private Document factory;
private Element current;
private DomListener listener;
public DomFilter (DomListener l)
{ listener = l; }
public void startDocument ()
throws SAXException
{
// all this just to get an empty document;
// we need one to use as a factory
try {
factory = DocumentBuilderFactory
.newInstance ()
.newDocumentBuilder ()
.newDocument ();
} catch (Exception e) {
throw new SAXException ("can't get DOM factory", e);
}
}
public void startElement (String uri, String local,
String qName, Attributes atts)
throws SAXException
{
// start a new subtree, or ignore
if (current == null) {
if (!listener.getURI ().equals (uri))
return;
if (!listener.getLocalName ().equals (local))
return;
current = factory.createElementNS (uri, qName);
// Add to current subtree, descend.
} else {
Element e;
if ("".equals (uri))
e = factory.createElement (qName);
else
e = factory.createElementNS (uri, qName);
current.appendChild (e);
current = e;
}
// NOTE: this example discards all attributes!
// They ought to be saved to the current element.
}
public void endElement (String uri, String local, String qName)
throws SAXException
{
Node parent;
// ignore?
if (current == null)
return;
parent = current.getParentNode ();
// end subtree?
if (parent == null) {
current.normalize ();
listener.processTree (current);
current = null;
// else climb up one level
} else
current = (Element) current.getParentNode ();
}
// if saving, append and continue
public void characters (char buf [], int offset, int length)
throws SAXException
{
if (current != null)
current.appendChild (factory.createTextNode (
new String (buf, offset, length)));
}
}
|