Sophie

Sophie

distrib > Mandriva > current > i586 > media > main-updates > by-pkgid > 8e6051afcdb111a0317a58fb64c2abf5 > files > 6537

qt4-doc-4.6.3-0.2mdv2010.2.i586.rpm

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- schema.qdoc -->
<head>
  <title>Qt 4.6: XML Schema Validation Example</title>
  <link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><a href="http://qt.nokia.com/"><img src="images/qt-logo.png" align="left" border="0" /></a></td>
<td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">All&nbsp;Functions</font></a>&nbsp;&middot; <a href="overviews.html"><font color="#004faf">Overviews</font></a></td></tr></table><h1 class="title">XML Schema Validation Example<br /><span class="subtitle"></span>
</h1>
<p>Files:</p>
<ul>
<li><a href="xmlpatterns-schema-mainwindow-cpp.html">xmlpatterns/schema/mainwindow.cpp</a></li>
<li><a href="xmlpatterns-schema-mainwindow-h.html">xmlpatterns/schema/mainwindow.h</a></li>
<li><a href="xmlpatterns-schema-schema-ui.html">xmlpatterns/schema/schema.ui</a></li>
<li><a href="xmlpatterns-schema-files-invalid-contact-xml.html">xmlpatterns/schema/files/invalid_contact.xml</a></li>
<li><a href="xmlpatterns-schema-files-invalid-order-xml.html">xmlpatterns/schema/files/invalid_order.xml</a></li>
<li><a href="xmlpatterns-schema-files-invalid-recipe-xml.html">xmlpatterns/schema/files/invalid_recipe.xml</a></li>
<li><a href="xmlpatterns-schema-files-valid-contact-xml.html">xmlpatterns/schema/files/valid_contact.xml</a></li>
<li><a href="xmlpatterns-schema-files-valid-order-xml.html">xmlpatterns/schema/files/valid_order.xml</a></li>
<li><a href="xmlpatterns-schema-files-valid-recipe-xml.html">xmlpatterns/schema/files/valid_recipe.xml</a></li>
<li><a href="xmlpatterns-schema-main-cpp.html">xmlpatterns/schema/main.cpp</a></li>
<li><a href="xmlpatterns-schema-schema-pro.html">xmlpatterns/schema/schema.pro</a></li>
<li><a href="xmlpatterns-schema-schema-qrc.html">xmlpatterns/schema/schema.qrc</a></li>
</ul>
<p>This example shows how to use <a href="qtxmlpatterns.html">QtXmlPatterns</a> to validate XML with a W3C XML Schema.</p>
<ul><li><a href="#introduction">Introduction</a></li>
<ul><li><a href="#the-user-interface">The User Interface</a></li>
<li><a href="#validating-xml-instance-documents">Validating XML Instance Documents</a></li>
</ul>
<li><a href="#code-walk-through">Code Walk-Through</a></li>
<ul><li><a href="#the-ui-class-mainwindow">The UI Class: MainWindow</a></li>
</ul>
</ul>
<a name="introduction"></a>
<h2>Introduction</h2>
<p>The example application shows different XML schema definitions and for every definition two XML instance documents, one that is valid according to the schema and one that is not. The user can select the valid or invalid instance document, change it and validate it again.</p>
<a name="the-user-interface"></a>
<h3>The User Interface</h3>
<p>The UI for this example was created using <a href="designer-manual.html">Qt Designer</a>:</p>
<p align="center"><img src="images/schema-example.png" /></p><p>The UI consists of three parts, at the top the XML schema <a href="qcombobox.html">selection</a> and the schema <a href="qtextbrowser.html">viewer</a>, below the XML instance <a href="qcombobox.html">selection</a> and the instance <a href="qtextedit.html">editor</a> and at the bottom the validation status <a href="qlabel.html">label</a> next to the validation <a href="qpushbutton.html">button</a>.</p>
<a name="validating-xml-instance-documents"></a>
<h3>Validating XML Instance Documents</h3>
<p>You can select one of the three predefined XML schemas and for each schema an valid or invalid instance document. A click on the 'Validate' button will validate the content of the XML instance editor against the schema from the XML schema viewer. As you can modify the content of the instance editor, different instances can be tested and validation error messages analysed.</p>
<a name="code-walk-through"></a>
<h2>Code Walk-Through</h2>
<p>The example's main() function creates the standard instance of <a href="qapplication.html">QApplication</a>. Then it creates an instance of the mainwindow class, shows it, and starts the Qt event loop:</p>
<pre> int main(int argc, char* argv[])
 {
     Q_INIT_RESOURCE(schema);
     QApplication app(argc, argv);
     MainWindow* const window = new MainWindow;
     window-&gt;show();
     return app.exec();
 }</pre>
<a name="the-ui-class-mainwindow"></a>
<h3>The UI Class: MainWindow</h3>
<p>The example's UI is a conventional Qt GUI application inheriting <a href="qmainwindow.html">QMainWindow</a> and the class generated by <a href="designer-manual.html">Qt Designer</a>:</p>
<pre> class MainWindow : public QMainWindow,
                    private Ui::SchemaMainWindow
 {
     Q_OBJECT

   public:
     MainWindow();

   private Q_SLOTS:
     void schemaSelected(int index);
     void instanceSelected(int index);
     void validate();
     void textChanged();

   private:
     void moveCursor(int line, int column);
 };</pre>
<p>The constructor fills the schema and instance <a href="qcombobox.html">QComboBox</a> selections with the predefined schemas and instances and connects their <a href="qcombobox.html#currentIndexChanged">currentIndexChanged()</a> signals to the window's <tt>schemaSelected()</tt> resp. <tt>instanceSelected()</tt> slot. Furthermore the signal-slot connections for the validation <a href="qpushbutton.html">button</a> and the instance <a href="qtextedit.html">editor</a> are set up.</p>
<p>The call to <tt>schemaSelected(0)</tt> and <tt>instanceSelected(0)</tt> will trigger the validation of the initial Contact Schema example.</p>
<pre> MainWindow::MainWindow()
 {
     setupUi(this);

     new XmlSyntaxHighlighter(schemaView-&gt;document());
     new XmlSyntaxHighlighter(instanceEdit-&gt;document());

     schemaSelection-&gt;addItem(tr(&quot;Contact Schema&quot;));
     schemaSelection-&gt;addItem(tr(&quot;Recipe Schema&quot;));
     schemaSelection-&gt;addItem(tr(&quot;Order Schema&quot;));

     instanceSelection-&gt;addItem(tr(&quot;Valid Contact Instance&quot;));
     instanceSelection-&gt;addItem(tr(&quot;Invalid Contact Instance&quot;));

     connect(schemaSelection, SIGNAL(currentIndexChanged(int)), SLOT(schemaSelected(int)));
     connect(instanceSelection, SIGNAL(currentIndexChanged(int)), SLOT(instanceSelected(int)));
     connect(validateButton, SIGNAL(clicked()), SLOT(validate()));
     connect(instanceEdit, SIGNAL(textChanged()), SLOT(textChanged()));

     validationStatus-&gt;setAlignment(Qt::AlignCenter | Qt::AlignVCenter);

     schemaSelected(0);
     instanceSelected(0);
 }</pre>
<p>In the <tt>schemaSelected()</tt> slot the content of the instance <a href="qcombobox.html">selection</a> is adapted to the selected schema and the corresponding schema is loaded from the <a href="resources.html">resource file</a> and displayed in the schema <a href="qtextbrowser.html">viewer</a>. At the end of the method a revalidation is triggered.</p>
<pre> void MainWindow::schemaSelected(int index)
 {
     instanceSelection-&gt;clear();
     if (index == 0) {
         instanceSelection-&gt;addItem(tr(&quot;Valid Contact Instance&quot;));
         instanceSelection-&gt;addItem(tr(&quot;Invalid Contact Instance&quot;));
     } else if (index == 1) {
         instanceSelection-&gt;addItem(tr(&quot;Valid Recipe Instance&quot;));
         instanceSelection-&gt;addItem(tr(&quot;Invalid Recipe Instance&quot;));
     } else if (index == 2) {
         instanceSelection-&gt;addItem(tr(&quot;Valid Order Instance&quot;));
         instanceSelection-&gt;addItem(tr(&quot;Invalid Order Instance&quot;));
     }
     textChanged();

     QFile schemaFile(QString(&quot;:/schema_%1.xsd&quot;).arg(index));
     schemaFile.open(QIODevice::ReadOnly);
     const QString schemaText(QString::fromUtf8(schemaFile.readAll()));
     schemaView-&gt;setPlainText(schemaText);

     validate();
 }</pre>
<p>In the <tt>instanceSelected()</tt> slot the selected instance is loaded from the <a href="resources.html">resource file</a> and loaded into the instance <a href="qtextedit.html">editor</a> an the revalidation is triggered again.</p>
<pre> void MainWindow::instanceSelected(int index)
 {
     QFile instanceFile(QString(&quot;:/instance_%1.xml&quot;).arg((2*schemaSelection-&gt;currentIndex()) + index));
     instanceFile.open(QIODevice::ReadOnly);
     const QString instanceText(QString::fromUtf8(instanceFile.readAll()));
     instanceEdit-&gt;setPlainText(instanceText);

     validate();
 }</pre>
<p>The <tt>validate()</tt> slot does the actual work in this example. At first it stores the content of the schema <a href="qtextbrowser.html">viewer</a> and the <a href="qtextedit.html">editor</a> into temporary <a href="qbytearray.html">variables</a>. Then it instanciates a <tt>MessageHandler</tt> object which inherits from <a href="qabstractmessagehandler.html">QAbstractMessageHandler</a> and is a convenience class to store error messages from the XmlPatterns system.</p>
<pre> class MessageHandler : public QAbstractMessageHandler
 {
     public:
         MessageHandler()
             : QAbstractMessageHandler(0)
         {
         }

         QString statusMessage() const
         {
             return m_description;
         }

         int line() const
         {
             return m_sourceLocation.line();
         }

         int column() const
         {
             return m_sourceLocation.column();
         }

     protected:
         virtual void handleMessage(QtMsgType type, const QString &amp;description,
                                    const QUrl &amp;identifier, const QSourceLocation &amp;sourceLocation)
         {
             Q_UNUSED(type);
             Q_UNUSED(identifier);

             m_messageType = type;
             m_description = description;
             m_sourceLocation = sourceLocation;
         }

     private:
         QtMsgType m_messageType;
         QString m_description;
         QSourceLocation m_sourceLocation;
 };</pre>
<p>After the <a href="qxmlschema.html">QXmlSchema</a> is instanciated and the message handler set on it, the <a href="qxmlschema.html#load">load()</a> method is called with the schema data as argument. If the schema is invalid or a parsing error has occured, <a href="qxmlschema.html#isValid">isValid()</a> returns <tt>false</tt> and the error is flagged in <tt>errorOccurred</tt>. If the loading was successful, a <a href="qxmlschemavalidator.html">QXmlSchemaValidator</a> is instanciated and the schema passed in the constructor. A call to <a href="qxmlschemavalidator.html#validate">validate()</a> will validate the passed XML instance data against the XML schema. The return value of that method signals whether the validation was successful. Depending on the success the status <a href="qlabel.html">label</a> is set to 'validation successful' or the error message stored in the <tt>MessageHandler</tt></p>
<p>The rest of the code does only some fancy coloring and eyecandy.</p>
<pre> void MainWindow::validate()
 {
     const QByteArray schemaData = schemaView-&gt;toPlainText().toUtf8();
     const QByteArray instanceData = instanceEdit-&gt;toPlainText().toUtf8();

     MessageHandler messageHandler;

     QXmlSchema schema;
     schema.setMessageHandler(&amp;messageHandler);

     schema.load(schemaData);

     bool errorOccurred = false;
     if (!schema.isValid()) {
         errorOccurred = true;
     } else {
         QXmlSchemaValidator validator(schema);
         if (!validator.validate(instanceData))
             errorOccurred = true;
     }

     if (errorOccurred) {
         validationStatus-&gt;setText(messageHandler.statusMessage());
         moveCursor(messageHandler.line(), messageHandler.column());
     } else {
         validationStatus-&gt;setText(tr(&quot;validation successful&quot;));
     }

     const QString styleSheet = QString(&quot;QLabel {background: %1; padding: 3px}&quot;)
                                       .arg(errorOccurred ? QColor(Qt::red).lighter(160).name() :
                                                            QColor(Qt::green).lighter(160).name());
     validationStatus-&gt;setStyleSheet(styleSheet);
 }</pre>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="40%" align="left">Copyright &copy; 2010 Nokia Corporation and/or its subsidiary(-ies)</td>
<td width="20%" align="center"><a href="trademarks.html">Trademarks</a></td>
<td width="40%" align="right"><div align="right">Qt 4.6.3</div></td>
</tr></table></div></address></body>
</html>