1 package com.jdon.util.jdom; 2 3 56 57 58 import java.util.Stack ; 59 60 import org.xml.sax.Attributes ; 61 import org.xml.sax.SAXException ; 62 import org.xml.sax.XMLReader ; 63 64 65 119 public class DataFormatFilter extends XMLFilterBase 120 { 121 122 123 124 128 129 132 public DataFormatFilter() 133 { 134 } 135 136 137 144 public DataFormatFilter(XMLReader xmlreader) 145 { 146 super(xmlreader); 147 } 148 149 150 154 155 166 public int getIndentStep () 167 { 168 return indentStep; 169 } 170 171 172 179 public void setIndentStep (int indentStep) 180 { 181 this.indentStep = indentStep; 182 } 183 184 185 186 190 191 197 public void reset () 198 { 199 state = SEEN_NOTHING; 200 stateStack = new Stack (); 201 } 202 203 204 205 209 210 219 public void startDocument () 220 throws SAXException 221 { 222 reset(); 223 super.startDocument(); 224 } 225 226 227 245 public void startElement (String uri, String localName, 246 String qName, Attributes atts) 247 throws SAXException 248 { 249 if (!stateStack.empty()) { 250 doNewline(); 251 doIndent(); 252 } 253 stateStack.push(SEEN_ELEMENT); 254 state = SEEN_NOTHING; 255 super.startElement(uri, localName, qName, atts); 256 } 257 258 259 276 public void endElement (String uri, String localName, String qName) 277 throws SAXException 278 { 279 boolean seenElement = (state == SEEN_ELEMENT); 280 state = stateStack.pop(); 281 if (seenElement) { 282 doNewline(); 283 doIndent(); 284 } 285 super.endElement(uri, localName, qName); 286 } 287 288 289 299 public void characters (char ch[], int start, int length) 300 throws SAXException 301 { 302 state = SEEN_DATA; 303 super.characters(ch, start, length); 304 } 305 306 307 308 312 313 319 private void doNewline () 320 throws SAXException 321 { 322 super.characters(NEWLINE, 0, NEWLINE.length); 323 } 324 325 326 332 private void doIndent () 333 throws SAXException 334 { 335 int n = indentStep * stateStack.size(); 336 if (n > 0) { 337 char ch[] = new char[n]; 338 for (int i = 0; i < n; i++) { 339 ch[i] = INDENT_CHAR; 340 } 341 super.characters(ch, 0, n); 342 } 343 } 344 345 346 347 348 352 private static final Object SEEN_NOTHING = new Object (); 353 private static final Object SEEN_ELEMENT = new Object (); 354 private static final Object SEEN_DATA = new Object (); 355 356 private static final char[] NEWLINE = new char[] {'\n'}; 357 private static final char INDENT_CHAR = ' '; 358 359 360 364 private Object state = SEEN_NOTHING; 365 private Stack stateStack = new Stack (); 366 367 private int indentStep = 0; 368 369 } 370 371 | Popular Tags |