SAXParser's
DefaultHandler provides a callback for public void characters(
public char[] ch, int start, int length, etc.) and throws a
SAXException for reading element text contents. You can read the
char array in any invocation of the
DefaultHandler and convert it into a String object for your use. However, this single
character() call is not sufficient to read entire element text.
Luckily, SAXParser's specifications allow parsers to split text data into multiple arrays and call characters multiple times. A better method would be to:
- Create a String or StringBuffer object in the startElement method:
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws
SAXException {
m_elemText = new StringBuffer();
}
- Append the text into the String or StringBuffer for each characters call:
public void characters(char[] ch, int start, int length) throws SAXException {
m_elemText.append(new String(ch, start, length) );
}
- In endElement, read the entire element text:
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
System.out.println(Element text: " + m_elemText.toString());
}
Complying with this SAX specification requirement can save you hours of debugging when you hit this limitation in a production environment.
If you have a hot tip and we publish it, we'll pay you. However, due to accounting overhead we no longer pay $10 for a single tip submission. You must accumulate 10 acceptable tips to receive payment. Be sure to include a clear explanation of what the technique does and why it's useful. If it includes code, limit it to 20 lines if possible.
Submit your tip here.