The SAX API for XML parsers was originally developed for
Java. Please be aware that there is no standard SAX API for
C++, and that use of the Xerces-C++ SAX API does not
guarantee client code compatibility with other C++ XML
parsers.
The SAX API presents a callback based API to the parser. An
application that uses SAX provides an instance of a handler
class to the parser. When the parser detects XML constructs,
it calls the methods of the handler class, passing them
information about the construct that was detected. The most
commonly used handler classes are DocumentHandler which is
called when XML constructs are recognized, and ErrorHandler
which is called when an error occurs. The header files for the
various SAX handler classes are in
'<xerces-c1_7_0>/include/xercesc/sax'
As a convenience, Xerces-C++ provides the class
HandlerBase, which is a single class which is publicly derived
from all the Handler classes. HandlerBase's default
implementation of the handler callback methods is to do
nothing. A convenient way to get started with Xerces-C++ is
to derive your own handler class from HandlerBase and override
just those methods in HandlerBase which you are interested in
customizing. This simple example shows how to create a handler
which will print element names, and print fatal error
messages. The source code for the sample applications show
additional examples of how to write handler classes.
This is the header file MySAXHandler.hpp:
 |  |  |
 | #include <xercesc/sax/HandlerBase.hpp>
class MySAXHandler : public HandlerBase {
public:
void startElement(const XMLCh* const, AttributeList&);
void fatalError(const SAXParseException&);
}; |  |
 |  |  |
This is the implementation file MySAXHandler.cpp:
 |  |  |
 | #include "MySAXHandler.hpp"
#include <iostream.h>
MySAXHandler::MySAXHandler()
{
}
MySAXHandler::startElement(const XMLCh* const name,
AttributeList& attributes)
{
// transcode() is an user application defined function which
// converts unicode strings to usual 'char *'. Look at
// the sample program SAXCount for an example implementation.
cout << "I saw element: " << transcode(name) << endl;
}
MySAXHandler::fatalError(const SAXParseException& exception)
{
cout << "Fatal Error: " << transcode(exception.getMessage())
<< " at line: " << exception.getLineNumber()
<< endl;
} |  |
 |  |  |
The XMLCh and AttributeList types are supplied by
Xerces-C++ and are documented in the include
files. Examples of their usage appear in the source code to
the sample applications.