1 54 package sax; 55 56 import java.util.Stack ; 57 58 import org.xml.sax.Attributes ; 59 import org.xml.sax.SAXException ; 60 import org.xml.sax.XMLReader ; 61 62 63 117 public class DataFormatFilter extends XMLFilterBase 118 { 119 120 121 122 126 127 130 public DataFormatFilter() 131 { 132 } 133 134 135 142 public DataFormatFilter(XMLReader xmlreader) 143 { 144 super(xmlreader); 145 } 146 147 148 152 153 164 public int getIndentStep () 165 { 166 return indentStep; 167 } 168 169 170 177 public void setIndentStep (int indentStep) 178 { 179 this.indentStep = indentStep; 180 } 181 182 183 184 188 189 195 public void reset () 196 { 197 state = SEEN_NOTHING; 198 stateStack = new Stack (); 199 } 200 201 202 203 207 208 217 public void startDocument () 218 throws SAXException 219 { 220 reset(); 221 super.startDocument(); 222 } 223 224 225 243 public void startElement (String uri, String localName, 244 String qName, Attributes atts) 245 throws SAXException 246 { 247 if (!stateStack.empty()) { 248 doNewline(); 249 doIndent(); 250 } 251 stateStack.push(SEEN_ELEMENT); 252 state = SEEN_NOTHING; 253 super.startElement(uri, localName, qName, atts); 254 } 255 256 257 274 public void endElement (String uri, String localName, String qName) 275 throws SAXException 276 { 277 boolean seenElement = (state == SEEN_ELEMENT); 278 state = stateStack.pop(); 279 if (seenElement) { 280 doNewline(); 281 doIndent(); 282 } 283 super.endElement(uri, localName, qName); 284 } 285 286 287 297 public void characters (char ch[], int start, int length) 298 throws SAXException 299 { 300 state = SEEN_DATA; 301 super.characters(ch, start, length); 302 } 303 304 305 306 310 311 317 private void doNewline () 318 throws SAXException 319 { 320 super.characters(NEWLINE, 0, NEWLINE.length); 321 } 322 323 324 330 private void doIndent () 331 throws SAXException 332 { 333 int n = indentStep * stateStack.size(); 334 if (n > 0) { 335 char ch[] = new char[n]; 336 for (int i = 0; i < n; i++) { 337 ch[i] = INDENT_CHAR; 338 } 339 super.characters(ch, 0, n); 340 } 341 } 342 343 344 345 346 350 private static final Object SEEN_NOTHING = new Object (); 351 private static final Object SEEN_ELEMENT = new Object (); 352 private static final Object SEEN_DATA = new Object (); 353 354 private static final char[] NEWLINE = new char[] {'\n'}; 355 private static final char INDENT_CHAR = ' '; 356 357 358 362 private Object state = SEEN_NOTHING; 363 private Stack stateStack = new Stack (); 364 365 private int indentStep = 0; 366 367 } 368 369 | Popular Tags |