Filter for removing formatting from data- or field-oriented XML.
This filter removes leading and trailing whitespace from
field-oriented XML without mixed content. Note that this class will
likely not yield appropriate results for document-oriented XML like
XHTML pages, which mix character data and elements together.
| Method from sax.DataUnformatFilter Detail: |
public void characters(char[] ch,
int start,
int length) throws SAXException {
if (state != SEEN_DATA) {
/* Look for non-whitespace. */
int end = start + length;
while (end-- > start) {
if (!isXMLWhitespace(ch[end]))
break;
}
/*
* If all the characters are whitespace, save them for later.
* If we've got some data, emit any saved whitespace and update
* our state to show we've seen data.
*/
if (end < start) {
saveWhitespace(ch, start, length);
} else {
state = SEEN_DATA;
emitWhitespace();
}
}
/* Pass on everything inside a data field. */
if (state == SEEN_DATA) {
super.characters(ch, start, length);
}
}
Filter a character data event. |
protected void clearWhitespace() {
whitespace.setLength(0);
}
Discards saved whitespace. |
protected void emitWhitespace() throws SAXException {
char[] data = new char[whitespace.length()];
whitespace.getChars(0, data.length, data, 0);
whitespace.setLength(0);
super.characters(data, 0, data.length);
}
Passes saved whitespace down the filter chain. |
public void endElement(String uri,
String localName,
String qName) throws SAXException {
if (state == SEEN_ELEMENT) {
clearWhitespace();
} else {
emitWhitespace();
}
state = stateStack.pop();
super.endElement(uri, localName, qName);
}
Filter an end element event. |
public void ignorableWhitespace(char[] ch,
int start,
int length) throws SAXException {
emitWhitespace();
// ignore
}
Filter an ignorable whitespace event. |
public void processingInstruction(String target,
String data) throws SAXException {
emitWhitespace();
super.processingInstruction(target, data);
}
Filter a processing instruction event. |
public void reset() {
state = SEEN_NOTHING;
stateStack = new Stack();
whitespace = new StringBuffer();
}
|
protected void saveWhitespace(char[] ch,
int start,
int length) {
whitespace.append(ch, start, length);
}
Saves trailing whitespace. |
public void startDocument() throws SAXException {
reset();
super.startDocument();
}
|
public void startElement(String uri,
String localName,
String qName,
Attributes atts) throws SAXException {
clearWhitespace();
stateStack.push(SEEN_ELEMENT);
state = SEEN_NOTHING;
super.startElement(uri, localName, qName, atts);
}
Filter a start element event. |