Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Fonctions  · 

Walkthrough: How to use the Qt SAX2 classes

For a general discussion of the XML topics in Qt please refer to the document XML Module. To learn more about SAX2 see the document describing the Qt SAX2 implementation.

Before reading on you should at least be familiar with the Introduction to SAX2.

A tiny parser

In this section we will present a small example reader that outputs the names of all elements in an XML document on the command line. The element names are indented corresponding to their nesting level.

As mentioned in Introduction to SAX2 we have to implement the functions of the handler classes that we are interested in. In our case these are only three: QXmlContentHandler::startDocument(), QXmlContentHandler::startElement() and QXmlContentHandler::endElement().

For this purpose we use a subclass of the QXmlDefaultHandler (remember that the special handler classes are all abstract and the default handler class provides an implementation that does not change the parsing behavior):

/****************************************************************************
** $Id: qt/structureparser.h   3.3.7   edited Aug 31 2005 $
**
** Copyright (C) 1992-2005 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef STRUCTUREPARSER_H
#define STRUCTUREPARSER_H

#include <qxml.h>

class QString;

class StructureParser : public QXmlDefaultHandler
{
public:
    bool startDocument();
    bool startElement( const QString&, const QString&, const QString& ,
                       const QXmlAttributes& );
    bool endElement( const QString&, const QString&, const QString& );

private:
    QString indent;
};

#endif

Apart from the private helper variable indent that we will use to get indentation right, there is nothing special about our new StructureParser class.

Even the implementation is straight-forward:

    #include "structureparser.h"

    #include <stdio.h>
    #include <qstring.h>

First we overload QXmlContentHandler::startDocument() with a non-empty version.

    bool StructureParser::startDocument()
    {
        indent = "";
        return TRUE;
    }

At the beginning of the document we simply set indent to an empty string because we want to print out the root element without any indentation. Also we return TRUE so that the parser continues without reporting an error.

Because we want to be informed when the parser comes accross a start tag of an element and subsequently print it out, we have to overload QXmlContentHandler::startElement().

    bool StructureParser::startElement( const QString&, const QString&,
                                        const QString& qName,
                                        const QXmlAttributes& )
    {
        printf( "%s%s\n", (const char*)indent, (const char*)qName );
        indent += "    ";
        return TRUE;
    }

This is what the implementation does: The name of the element with preceding indentation is printed out followed by a linebreak. Strictly speaking qName contains the local element name without an eventual prefix denoting the namespace.

If another element follows before the current element's end tag it should be indented. Therefore we add four spaces to the indent string.

Finally we return TRUE in order to let the parser continue without errors.

The last functionality we need to add is the parser's behaviour when an end tag occurs. This means overloading QXmlContentHandler::endElement().

    bool StructureParser::endElement( const QString&, const QString&, const QString& )
    {
        indent.remove( (uint)0, 4 );
        return TRUE;
    }

Obviously we then should shorten the indent string by the four whitespaces added in startElement().

With this we're done with our parser and can start writing the main() program.

    #include "structureparser.h"
    #include <qfile.h>
    #include <qxml.h>
    #include <qwindowdefs.h>

    int main( int argc, char **argv )
    {
        if ( argc < 2 ) {
            fprintf( stderr, "Usage: %s <xmlfile> [<xmlfile> ...]\n", argv[0] );
            return 1;
        }

This check ensures that we have a sequence of files from the command line to examine.

        StructureParser handler;

The next step is to create an instance of the StructureParser.

        QXmlSimpleReader reader;
        reader.setContentHandler( &handler );

After that we set up the reader. As our StructureParser class deals with QXmlContentHandler functionality only we simply register it as the content handler of our choice.

        for ( int i=1; i < argc; i++ ) {

Successively we deal with all files given as command line arguments.

            QFile xmlFile( argv[i] );
            QXmlInputSource source( &xmlFile );

Then we create a QXmlInputSource for the XML file to be parsed.

            reader.parse( source );

Now we take our input source and start parsing.

        }
        return 0;
    }

Running the program on the following XML file...

<animals>
<mammals>
  <monkeys> <gorilla/> <orangutan/> </monkeys>
</mammals>
<birds> <pigeon/> <penguin/> </birds>
</animals>

... produces the following output:

animals
    mammals
        monkeys
            gorilla
            orang-utan
    birds
        pigeon
        penguin 

It will however refuse to produce the correct result if you e.g. insert a whitespace between a < and the element name in your test-XML file. To prevent such annoyances you should always install an error handler with QXmlReader::setErrorHandler(). This allows you to report parsing errors to the user.

See also Step-by-step Examples.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 65
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. BlackBerry 10 : premières images du prochain OS de RIM qui devrait intégrer des widgets et des tuiles inspirées de Windows Phone 0
  5. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. La rubrique Qt a besoin de vous ! 1
Page suivante

Le blog Digia au hasard

Logo

Créer des applications avec un style Metro avec Qt, exemples en QML et C++, un article de Digia Qt traduit par Thibaut Cuvelier

Le blog Digia est l'endroit privilégié pour la communication sur l'édition commerciale de Qt, où des réponses publiques sont apportées aux questions les plus posées au support. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 3.3
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web