1 16 17 18 package org.apache.tester; 19 20 21 import java.net.URL ; 22 import org.xml.sax.AttributeList ; 23 import org.xml.sax.HandlerBase ; 24 import org.xml.sax.Parser ; 25 import org.xml.sax.SAXException ; 26 import org.xml.sax.SAXParseException ; 27 import org.xml.sax.helpers.ParserFactory ; 28 29 30 38 39 public class Xerces01Parser extends HandlerBase { 40 41 42 44 45 48 protected int attributes = 0; 49 50 51 54 protected int characters = 0; 55 56 57 60 protected int elements = 0; 61 62 63 66 protected int whitespace = 0; 67 68 69 70 72 73 80 public void parse(URL url) throws Exception { 81 82 Parser parser = 84 ParserFactory.makeParser("org.apache.xerces.parsers.SAXParser"); 85 parser.setDocumentHandler(this); 86 parser.setErrorHandler(this); 87 88 long before = System.currentTimeMillis(); 90 parser.parse(url.toString()); 91 long after = System.currentTimeMillis(); 92 93 StaticLogger.write("Parsing time = " + (after - before) + 95 " milliseconds"); 96 StaticLogger.write("Processed " + elements + " elements"); 97 StaticLogger.write("Processed " + attributes + " attributes"); 98 StaticLogger.write("Processed " + characters + " characters"); 99 StaticLogger.write("Processed " + whitespace + " whitespaces"); 100 101 } 102 103 104 106 107 114 public void error(SAXParseException e) throws SAXException { 115 116 StaticLogger.write("[Error] " + 117 getLocationString(e) + ": " + 118 e.getMessage()); 119 120 } 121 122 123 130 public void fatalError(SAXParseException e) throws SAXException { 131 132 StaticLogger.write("[Fatal] " + 133 getLocationString(e) + ": " + 134 e.getMessage()); 135 136 } 137 138 139 146 public void warning(SAXParseException e) throws SAXException { 147 148 StaticLogger.write("[Warning] " + 149 getLocationString(e) + ": " + 150 e.getMessage()); 151 152 } 153 154 155 160 private String getLocationString(SAXParseException e) { 161 162 StringBuffer sb = new StringBuffer (); 163 String systemId = e.getSystemId(); 164 if (systemId != null) { 165 int index = systemId.lastIndexOf('/'); 166 if (index != -1) 167 systemId = systemId.substring(index + 1); 168 sb.append(systemId); 169 } 170 sb.append(':'); 171 sb.append(e.getLineNumber()); 172 sb.append(':'); 173 sb.append(e.getColumnNumber()); 174 return (sb.toString()); 175 176 } 177 178 179 181 182 191 public void characters(char ch[], int start, int length) 192 throws SAXException { 193 194 characters += length; 195 196 } 197 198 199 208 public void ignorableWhitespace(char ch[], int start, int length) 209 throws SAXException { 210 211 whitespace += length; 212 213 } 214 215 216 224 public void startElement(String name, AttributeList attrs) { 225 226 elements++; 227 if (attrs != null) 228 attributes += attrs.getLength(); 229 230 } 231 232 233 234 } 235 | Popular Tags |