The most important characteristic of SAX parser is that it traverses the entire xml tree only once, from top to bottom. There is no intermediate memory for the element nodes, as in DOM parser. Therefore, SAX parser is memory efficient but cannot traverse backwards.
How the SAX parser works? By serveral events and their event handlers:
startElement
endElement
characters
Here is an example of a Qt SAX parser, which is a subclass of QXmlDefaultHandler.
=========================================
<Items>
<Item>
<Material>all purpose flour, stir before measuring</Material>
<Mount Unit="cups">3</Mount>
</Item>
<Item>
<Material>1 1/2 teaspoons baking soda</Material>
</Item>
<Item>
<Material>1 1/2 teaspoons ground cinnamon</Material>
</Item>
<Item>
<Material>8 ounces unsalted butter</Material>
</Item>
</Items>
=========================================
#include <QtXml/qxml.h>
#include <QString>
static const char TAG_ITEM[] = "Item";
static const char TAG_MATERIAL[]= "Material";
static const char TAG_MOUNT[] = "Mount";
class MyParser : public QXmlDefaultHandler
{
public:
bool startElement( const QString & namespaceURI,
const QString & localName,
const QString & qName,
const QXmlAttributes & atts )
{
if( localName == TAG_ITEM) {}
else if( localName == TAG_MATERIAL ) {}
else if( localName == TAG_MOUNT ){}
else{return false;}
currElement_ = localName;
return true;
}
bool characters ( const QString& ch_in)
{
if( currElement_ == TAG_ITEM) {}
else if( currElement_ == TAG_MATERIAL ) {}
else if( currElement_ == TAG_MOUNT ){}
else{return false;}
return true;
}
bool endElement( const QString&, const QString& localName, const QString& )
{
if( localName == TAG_ITEM) {}
else if( localName == TAG_MATERIAL ) {}
else if( localName == TAG_MOUNT ){}
else{return false;}
currElement_ = localName;
return true;
}
private:
QString currElement_;
};
No comments:
Post a Comment