sax2.cpp
An example showing XML serialization that is performed using SAX2.
#include <iostream>
#include <zorba/zorba.h>
#include <zorba/default_content_handler.h>
#include <zorba/store_manager.h>
#include <zorba/zorba_exception.h>
using namespace zorba;
class XMLSerializer: public DefaultContentHandler
{
protected:
std::ostream& theOStream;
bool preserveWhiteSpaces;
public:
XMLSerializer( std::ostream & aOStream, bool useWS = true )
: theOStream( aOStream ),
preserveWhiteSpaces( useWS ){}
virtual ~XMLSerializer(){}
void endDocument()
{
theOStream << std::endl;
}
void startElement( const String &uri, const String &localname,
const String &qname, const SAX2_Attributes& attrs )
{
theOStream << "<" << qname;
for ( unsigned int i = 0; i < attrs.getLength(); i++ ) {
theOStream << " " << attrs.getQName( i ) << "=\"" << attrs.getValue( i ) << "\"";
}
theOStream << ">";
}
void endElement( const String &uri, const String &localname, const String &qname )
{
theOStream << "</" << qname << ">";
}
void characters( const String & text )
{
theOStream << text;
}
void processingInstruction( const String &target, const String &data ){}
void ignorableWhitespace( const String & whitespace )
{
if ( preserveWhiteSpaces ) {
theOStream << whitespace;
}
}
};
int sax2( int argc, char * argv[] )
{
XMLSerializer lContentHandler( std::cout );
void* lStore = zorba::StoreManager::getStore();
Zorba* lZorba = Zorba::getInstance(lStore);
try
{
XQuery_t lQuery = lZorba->compileQuery("<a xmlns:f=\"foo\" xmlns=\"http://zorba.io/defaultns\"> text a text a <b xmlns:ns1=\"http://zorba.io/usecase1\" attr1=\"value1\" attr2=\"value2\"> text b </b><f:bar>foo</f:bar><foo /><bar /><b><![CDATA[ foo ]]></b></a>");
lQuery->registerSAXHandler( &lContentHandler );
lQuery->executeSAX();
}
catch ( ZorbaException &e )
{
std::cerr << e << std::endl;
}
lZorba->shutdown();
zorba::StoreManager::shutdownStore(lStore);
return 0;
}