1 16 package org.apache.cocoon.xml; 17 18 import org.apache.cocoon.xml.AbstractXMLPipe; 19 20 import org.xml.sax.Attributes ; 21 import org.xml.sax.ContentHandler ; 22 import org.xml.sax.SAXException ; 23 24 31 public class WhitespaceFilter extends AbstractXMLPipe { 32 private StringBuffer buffer = null; 33 34 39 public WhitespaceFilter(ContentHandler handler) { 40 setContentHandler(handler); 41 } 42 43 46 public void characters(char c[], int start, int len) throws SAXException { 47 if (contentHandler==null) { 48 return; 49 } 50 51 if (buffer==null) { 52 buffer = new StringBuffer (); 53 } 54 55 buffer.append(c, start, len); 56 } 57 58 61 public void ignorableWhitespace(char c[], int start, 62 int len) throws SAXException { 63 } 65 66 69 public void startElement(String namespaceURI, String localName, 70 String qName, 71 Attributes atts) throws SAXException { 72 73 pushText(); 74 contentHandler.startElement(namespaceURI, localName, qName, atts); 75 } 76 77 80 public void endElement(String uri, String loc, String raw) 81 throws SAXException { 82 83 pushText(); 84 contentHandler.endElement(uri, loc, raw); 85 } 86 87 90 public void processingInstruction(String target, String data) 91 throws SAXException { 92 93 pushText(); 94 contentHandler.processingInstruction(target, data); 95 } 96 97 104 public void comment(char ch[], int start, int len) 105 throws SAXException { 106 107 pushText(); 108 super.comment(ch, start, len); 109 } 110 111 112 public void pushText() throws SAXException { 113 114 if (buffer!=null) { 115 String text = buffer.toString(); 116 117 StringBuffer normalized = new StringBuffer (); 118 119 for(int i=0; i<text.length(); i++) { 120 if (Character.isWhitespace(text.charAt(i))) { 121 normalized.append(' '); 122 while (((i+1)<text.length()) && (Character.isWhitespace(text.charAt(i+1)))) 123 i++; 124 } else { 125 normalized.append(text.charAt(i)); 126 } 127 } 128 129 text = normalized.toString().trim(); 130 131 if (text.length()>0) { 132 contentHandler.characters(text.toCharArray(), 0, 133 text.length()); 134 } 135 136 buffer = null; 137 } 138 } 139 } 140 | Popular Tags |