How to use SAX Filter in XML
In this article I am going to explain about SAX Filter in XML.
SAX Filter in XML
A SAX filter is a SAX parser like XML Reader, Except that it obtain event from another XML Reader rather than primary source XML document or database. Filter can modify a stream of event and pass on to the final application. SAX filter are implemented by sub classing the org.XML.SAX.helpers.XMLFilterlmpl class. This class implements all the required interfaces of SAX for both parsers and client applications. A SAX filter sits between parser and client application and intercept the message that these two object pass to each other. It can pass this message to client application in form of unchanged, modify, replace, block. To client application the filter look like a parser that is XMLReader. To parser the filter look like a client application that is ContentHendler.
This step should be done at the time of using filter
- Create a filter object. Invoking by its own constrictor.
- Create the XMLReader that will pass the document by calling XMLReaderFactory.createXMLReader().
- Attached the filter to parser using the filter stepparent() method.
- Install the contentHandler in the filter
- parse the document by calling filter's parse() method.
A filter that remove processing instruction
A SAX filter that convert processing Instruction in element.
If you want to replace processing Instruction with an element whose name are same.
import org.xml.sax
import org.xml.sax.helpers
public class ProcessingInstructionConverter extends XMLFilterImpl {
public void processingInstruction(String target, String data)
throws SAXException {
startElement( );
Attributes emptyAttributes = new AttributesImpl( );
startElement("", target, target, emptyAttributes);
char[] text = data.toCharArray( );
characters(text, 0, text.length);
endElement("", target, target);
} }
|
A SAX filter that convert text to uppercase
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);
}
}
|
Further Readings
You may also want to read these related articles: here
Ask Your Question
Got a programming related question? You may want to post your question here