Besides elements defined in our DTD, XML has a set of already predefined ones. These are comments, character data (CDATA) etc. Character data is a text directly inserted between start and end tags of the element. It can mix with children tagged-elements.

A concrete implementation of SAX-parser defines whether it will collect all CDATA before passage to handler or it will pass it there by their occurence.

Example below specifies how to handle CDATA blocks:

 import java.util.Stack;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * This example demonstrates how to extract text (CDATA) information
 * from the element in the source XML-document.
 */

public class SampleOfCDataAccess extends DefaultHandler {
  private Stack currentElement = new Stack();

  // we push current element name:
  public void startElement (String uri, String localName,
    String qName, Attributes attrs) throws SAXException {

    currentElement.push(qName);
  }

  public void endElement(String namespaceURI, String localName,
    String qName) throws SAXException {

    currentElement.pop();
  }

  // this method will be called for each character-section occurred;
  // if the element containes several CDATA-sections mixed with
  // child elements the number of calls depends on SAX-implementation:
  public void characters(char[] ch, int start, int length)
    throws SAXException {

    String cdata = new String(ch, start, length);

    System.out.println("Element '" + currentElement.peek()
      + "' contains text: " + cdata);
  }

  public static void main(String[] args) {
    try {
      // creates and returns new instance of SAX-implementation:
      SAXParserFactory factory = SAXParserFactory.newInstance();
      factory.setValidating(true);

      // create SAX-parser...
      SAXParser parser = factory.newSAXParser();


      parser.parse("sample.xml", new SampleOfCDataAccess());

    } catch (Exception ex) {
      ex.printStackTrace(System.out);
    }
  }
}