欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

DOM解析XML时的 Event Handler,domhandler,/** <a href

来源: javaer 分享于  点击 36663 次 点评:31

DOM解析XML时的 Event Handler,domhandler,/**
/**  <a href="http://www.oreilly.com/catalog/sax2/">http://www.oreilly.com/catalog/sax2/ * SAX2 *   By David Brownell *   First Edition January 2002 *   ISBN: 0-596-00237-8 */import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;// a kind of event handlerinterface 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)));    }}//该片段来自于http://byrx.net

相关栏目:

用户点评