saxcounter.java

来自「写xml文件的相关类,可以直接应用到项目」· Java 代码 · 共 81 行

JAVA
81
字号
package xmlwriter;import java.io.File;import java.io.IOException;import java.util.Enumeration;import java.util.Hashtable;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;public class SAXCounter extends DefaultHandler {    private Hashtable tags;    // Parser calls this once at the beginning of a document    public void startDocument() throws SAXException {        tags = new Hashtable();    }    public void endDocument() throws SAXException {        Enumeration e = tags.keys();        while (e.hasMoreElements()) {            String tag = (String)e.nextElement();            int count = ((Integer)tags.get(tag)).intValue();            System.out.println("Tag <" + tag + "> occurs " + count                               + " times");        }    }        // Parser calls this for each element in a document    public void startElement(String namespaceURI, String localName,                             String rawName, Attributes atts)	throws SAXException    {        String key = localName;        Object value = tags.get(key);        if (value == null) {            // Add a new entry            tags.put(key, new Integer(1));        } else {            // Get the current count and increment it            int count = ((Integer)value).intValue();            count++;            tags.put(key, new Integer(count));        }    }        static public void main(String[] args) {        String filename = null;        boolean validation = false;        filename="links.xml";        SAXParserFactory spf = SAXParserFactory.newInstance();//        XMLReader xmlReader = null;        SAXParser saxParser=null;        try {            // Create a JAXP SAXParser            saxParser = spf.newSAXParser();            // Get the encapsulated SAX XMLReader            //xmlReader = saxParser.getXMLReader();        } catch (Exception ex) {            System.err.println(ex);            System.exit(1);        }        try {            saxParser.parse(new File(filename),new SAXCounter());        } catch (SAXException se) {            System.err.println(se.getMessage());            System.exit(1);        } catch (IOException ioe) {            System.err.println(ioe);            System.exit(1);        }    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?