Development/Tutorials/Programming Tutorial KDE 4/How to write an XML parser
A parser is used to distinguish between formal language and bulk data of a given grammar. See en.wikipedia.org/wiki/Parser if in doubt. There are two ways to write a parser: to split up the content of a file into an object as known from object-oriented programming or to trigger a function everytime a reader occurs a given syntax tag. In the following code, a function is triggered for every time an html tag is found in a file. The first file is hello.cpp: <highlightSyntax language="cpp"> /* hello.cpp compile it with g++ -I. -I/home/kde-devel/kde/include -I/home/kde-devel/qt-unstable/include/Qt -I/home/kde-devel/qt-unstable/include -I/home/kde-devel/qt-unstable/include/QtXml parser.h parser.cpp hello.cpp -L/home/kde-devel/kde/lib -L/home/kde-devel/qt-unstable/lib -lQtCore_debug -lQtXml_debug -lkdeui
- /
- include <qstring.h>
- include <QXmlInputSource>
- include <qfile.h>
- include <parser.h>
int main() {
Parser* handler=new Parser(); QXmlInputSource* source=new QXmlInputSource(new QFile("hello.htm")); QXmlSimpleReader reader; reader.setContentHandler( handler ); reader.parse( source );
} </highlightSyntax>