XML technologies / XML / XML in a Nutshell / The Simple API for XML (SAX) / Filters

(Excerpt from “XML in a Nutshell” by Elliotte Rusty Harold & W. Scott Means)

A SAX filter sits between the parser and the application that called it. It intercepts messages exchanged between the two objects. The filter may leave messages unchanged, or modify, replace or block them. To the calling application, the filter looks like a parser, that is, an XMLReader. To the parser, the filter looks like a client application, that is, a ContentHandler.

SAX filters are imported by writing a subclass of org.xml.sax.helpers.XMLFilterImpl.

Note: There is also an interface org.xml.sax.XMLFilter. For most uses, however, it behaves in exactly the wrong direction. It filters messages from client to parser, rather than the far more important messages from parser to client. Implementing the interface XMLFilter directly also takes far more work than subclassing XMLFilterImpl. Experienced SAX programmers would almost never implement XMLFilter directly, preferring to subclass the adapter class XMLFilterImpl.

This class implements all required SAX interfaces, for both parser and client application. Its signature therefore looks like this:

public class XMLFilterImpl implements XMLFilter, XMLReader, ContentHandler, DTDHandler, ErrorHandler

To create your own filters, extend this class and override the methods corresponding to messages you want to filter. To remove all processing instructions, for example, write a filter overriding the method processingInstruction( ) to return nothing, as in the following code example.

import org.xml.sax.helpers.XMLFilterImpl;

public class ProcessingInstructionStripper extends XMLFilterImpl {

  public void processingInstruction(String target, String data) {
    // Weil hier nichts gemacht wird, werden Verarbeitungsanweisungen aus dem
    // Dokument *nicht* an den Client weitergegeben
  }

}

Code example: A SAX filter that removes processing instructions

If instead you want to replace a processing instruction with an element whose name matches its target and whose content matches its data, call from the method processingInstruction( ) the methods startElement( ), characters( ) and endElement( ) after filling the arguments with the appropriate processing-instruction data, as shown below:

import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class ProcessingInstructionConverter extends XMLFilterImpl {

  public void processingInstruction(String target, String data)
   throws SAXException {

    // AttributesImpl ist eine Adapterklasse im Package org.xml.sax.ext genau für
    // diesen Zweck. Wir möchten keine Attribute angeben, aber wir müssen ein viertes
    // Argument an startElement(  ) übergeben.
    Attributes emptyAttributes = new AttributesImpl(  );

    // Wir verwenden keinen Namensraum für das Element
    startElement("", target, target, emptyAttributes);
    // Es konvertiert String-Daten in char-Arrays.
    char[] text = data.toCharArray(  );
    characters(text, 0, text.length);

    endElement("", target, target);

  }
}

Code example: A SAX filter that converts processing instructions to elements

We used this filter to pass the code example A simple XML document to a program that outputs an XML document to System.out and were a little surprised by the following result:

<xml-stylesheet>type="text/css" href="person.css"</xml-stylesheet>
<person xmlns="http://xml.oreilly.com/person">
  <name:name xmlns:name="http://xml.oreilly.com/name">
    <name:vorname>Sydney</name:vorname>
    <name:nachname>Lee</name:nachname>
  </name:name>
  <auftrag project_id="p2"></auftrag>
</person>

This document is not well-formed! The problem is that the document contains two independent root elements. On reflection, that is not surprising. The well-formedness is normally checked by the parser as it reads the document structure. SAX filters should provide well-formed XML to client applications, but are not required to do so. They can in fact produce data far less well-formed than this example: unclosed start-tags, text containing forbidden characters such as form feeds or vertical tabs, or characters forbidden in names, such as * and §, in XML names. Do not simply assume that data from an XML filter is valid or well-formed.

To call a method without filtering it, or execute the same method in the underlying handler, you can add a prefix to the call using the keyword super. This invokes the superclass version. By default, every method in XMLFilterImpl simply passes the same arguments to the corresponding method in the parent handler. The next example demonstrates this with a filter that converts all character data to uppercase by overriding the method characters( ).

import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class UpperCaseFilter extends XMLFilterImpl {

  public void characters(char[] text, int start, int length)
   throws SAXException {

    String temp = new String(text, start, length);
    temp = temp.toUpperCase(  );
    text = temp.toCharArray(  );
    super.characters(text, 0, text.length);

  }

}

Code example: A SAX filter that converts text to uppercase

Applying a filter involves these steps:

  1. Create a filter object, normally by calling its own constructor.

  2. Create the XMLReader that will actually parse the document, normally by calling XMLReaderFactory.createXMLReader( ).

  3. Register the filter with the parser by calling the filter’s method setParent( ).

  4. Set up a ContentHandler in the filter.

  5. Parse the document by calling the filter’s method parse( ).

Details may vary slightly between applications. For example, you might configure handlers other than the ContentHandler or replace the parent handler between documents. In any case, once the filter is registered with the underlying XMLReader, do not call the underlying parser’s methods directly. Communicate with the parser only through the filter. The following example shows how to use the previous filter to parse a document:

XMLFilter filter = new UpperCaseFilter(  );
filter.setParent(XMLReaderFactory.createXMLReader(  ));
filter.setContentHandler(yourContentHandlerObject);
filter.parse(document);

Note that the filter’s method parse( ) is called, rather than the underlying parser’s method parse( ).

  

 

 

 

back to top