1
<?xml version="1.0" encoding="iso-8859-1"?>
3
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
4
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
7
<title>Qt 4.6: XML Schema Validation Example</title>
8
<link href="classic.css" rel="stylesheet" type="text/css" />
11
<table border="0" cellpadding="0" cellspacing="0" width="100%">
13
<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>
14
<td width="1"> </td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a> · <a href="classes.html"><font color="#004faf">All Classes</font></a> · <a href="functions.html"><font color="#004faf">All Functions</font></a> · <a href="overviews.html"><font color="#004faf">Overviews</font></a></td><td class="searchBar" align="right" valign="center"><form action="http://www.google.com/cse" id="cse-search-box"><div><input type="hidden" name="cx" value="000136343326384750312:dhbxnqlakyu" /><input type="hidden" name="ie" value="UTF-8" /><input type="text" name="q" size="31" /><input type="submit" name="sa" value="Search" /></div></form></td>
15
</tr></table><h1 class="title">XML Schema Validation Example<br /><span class="subtitle"></span>
19
<li><a href="xmlpatterns-schema-mainwindow-cpp.html">xmlpatterns/schema/mainwindow.cpp</a></li>
20
<li><a href="xmlpatterns-schema-mainwindow-h.html">xmlpatterns/schema/mainwindow.h</a></li>
21
<li><a href="xmlpatterns-schema-schema-ui.html">xmlpatterns/schema/schema.ui</a></li>
22
<li><a href="xmlpatterns-schema-files-invalid-contact-xml.html">xmlpatterns/schema/files/invalid_contact.xml</a></li>
23
<li><a href="xmlpatterns-schema-files-invalid-order-xml.html">xmlpatterns/schema/files/invalid_order.xml</a></li>
24
<li><a href="xmlpatterns-schema-files-invalid-recipe-xml.html">xmlpatterns/schema/files/invalid_recipe.xml</a></li>
25
<li><a href="xmlpatterns-schema-files-valid-contact-xml.html">xmlpatterns/schema/files/valid_contact.xml</a></li>
26
<li><a href="xmlpatterns-schema-files-valid-order-xml.html">xmlpatterns/schema/files/valid_order.xml</a></li>
27
<li><a href="xmlpatterns-schema-files-valid-recipe-xml.html">xmlpatterns/schema/files/valid_recipe.xml</a></li>
28
<li><a href="xmlpatterns-schema-main-cpp.html">xmlpatterns/schema/main.cpp</a></li>
29
<li><a href="xmlpatterns-schema-schema-pro.html">xmlpatterns/schema/schema.pro</a></li>
30
<li><a href="xmlpatterns-schema-schema-qrc.html">xmlpatterns/schema/schema.qrc</a></li>
32
<p>This example shows how to use <a href="qtxmlpatterns.html">QtXmlPatterns</a> to validate XML with a W3C XML Schema.</p>
33
<ul><li><a href="#introduction">Introduction</a></li>
34
<ul><li><a href="#the-user-interface">The User Interface</a></li>
35
<li><a href="#validating-xml-instance-documents">Validating XML Instance Documents</a></li>
37
<li><a href="#code-walk-through">Code Walk-Through</a></li>
38
<ul><li><a href="#the-ui-class-mainwindow">The UI Class: MainWindow</a></li>
41
<a name="introduction"></a>
43
<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>
44
<a name="the-user-interface"></a>
45
<h3>The User Interface</h3>
46
<p>The UI for this example was created using <a href="designer-manual.html">Qt Designer</a>:</p>
47
<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>
48
<a name="validating-xml-instance-documents"></a>
49
<h3>Validating XML Instance Documents</h3>
50
<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>
51
<a name="code-walk-through"></a>
52
<h2>Code Walk-Through</h2>
53
<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>
54
<pre> int main(int argc, char* argv[])
56
Q_INIT_RESOURCE(schema);
57
QApplication app(argc, argv);
58
MainWindow* const window = new MainWindow;
62
<a name="the-ui-class-mainwindow"></a>
63
<h3>The UI Class: MainWindow</h3>
64
<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>
65
<pre> class MainWindow : public QMainWindow,
66
private Ui::SchemaMainWindow
74
void schemaSelected(int index);
75
void instanceSelected(int index);
80
void moveCursor(int line, int column);
82
<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>
83
<p>The call to <tt>schemaSelected(0)</tt> and <tt>instanceSelected(0)</tt> will trigger the validation of the initial Contact Schema example.</p>
84
<pre> MainWindow::MainWindow()
88
new XmlSyntaxHighlighter(schemaView->document());
89
new XmlSyntaxHighlighter(instanceEdit->document());
91
schemaSelection->addItem(tr("Contact Schema"));
92
schemaSelection->addItem(tr("Recipe Schema"));
93
schemaSelection->addItem(tr("Order Schema"));
95
instanceSelection->addItem(tr("Valid Contact Instance"));
96
instanceSelection->addItem(tr("Invalid Contact Instance"));
98
connect(schemaSelection, SIGNAL(currentIndexChanged(int)), SLOT(schemaSelected(int)));
99
connect(instanceSelection, SIGNAL(currentIndexChanged(int)), SLOT(instanceSelected(int)));
100
connect(validateButton, SIGNAL(clicked()), SLOT(validate()));
101
connect(instanceEdit, SIGNAL(textChanged()), SLOT(textChanged()));
103
validationStatus->setAlignment(Qt::AlignCenter | Qt::AlignVCenter);
108
<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>
109
<pre> void MainWindow::schemaSelected(int index)
111
instanceSelection->clear();
113
instanceSelection->addItem(tr("Valid Contact Instance"));
114
instanceSelection->addItem(tr("Invalid Contact Instance"));
115
} else if (index == 1) {
116
instanceSelection->addItem(tr("Valid Recipe Instance"));
117
instanceSelection->addItem(tr("Invalid Recipe Instance"));
118
} else if (index == 2) {
119
instanceSelection->addItem(tr("Valid Order Instance"));
120
instanceSelection->addItem(tr("Invalid Order Instance"));
124
QFile schemaFile(QString(":/schema_%1.xsd").arg(index));
125
schemaFile.open(QIODevice::ReadOnly);
126
const QString schemaText(QString::fromUtf8(schemaFile.readAll()));
127
schemaView->setPlainText(schemaText);
131
<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>
132
<pre> void MainWindow::instanceSelected(int index)
134
QFile instanceFile(QString(":/instance_%1.xml").arg((2*schemaSelection->currentIndex()) + index));
135
instanceFile.open(QIODevice::ReadOnly);
136
const QString instanceText(QString::fromUtf8(instanceFile.readAll()));
137
instanceEdit->setPlainText(instanceText);
141
<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>
142
<pre> class MessageHandler : public QAbstractMessageHandler
146
: QAbstractMessageHandler(0)
150
QString statusMessage() const
152
return m_description;
157
return m_sourceLocation.line();
162
return m_sourceLocation.column();
166
virtual void handleMessage(QtMsgType type, const QString &description,
167
const QUrl &identifier, const QSourceLocation &sourceLocation)
170
Q_UNUSED(identifier);
172
m_messageType = type;
173
m_description = description;
174
m_sourceLocation = sourceLocation;
178
QtMsgType m_messageType;
179
QString m_description;
180
QSourceLocation m_sourceLocation;
182
<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>
183
<p>The rest of the code does only some fancy coloring and eyecandy.</p>
184
<pre> void MainWindow::validate()
186
const QByteArray schemaData = schemaView->toPlainText().toUtf8();
187
const QByteArray instanceData = instanceEdit->toPlainText().toUtf8();
189
MessageHandler messageHandler;
192
schema.setMessageHandler(&messageHandler);
194
schema.load(schemaData);
196
bool errorOccurred = false;
197
if (!schema.isValid()) {
198
errorOccurred = true;
200
QXmlSchemaValidator validator(schema);
201
if (!validator.validate(instanceData))
202
errorOccurred = true;
206
validationStatus->setText(messageHandler.statusMessage());
207
moveCursor(messageHandler.line(), messageHandler.column());
209
validationStatus->setText(tr("validation successful"));
212
const QString styleSheet = QString("QLabel {background: %1; padding: 3px}")
213
.arg(errorOccurred ? QColor(Qt::red).lighter(160).name() :
214
QColor(Qt::green).lighter(160).name());
215
validationStatus->setStyleSheet(styleSheet);
217
<p /><address><hr /><div align="center">
218
<table width="100%" cellspacing="0" border="0"><tr class="address">
219
<td width="40%" align="left">Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies)</td>
220
<td width="20%" align="center"><a href="trademarks.html">Trademarks</a></td>
221
<td width="40%" align="right"><div align="right">Qt 4.6.0</div></td>
222
<script type="text/javascript" src="http://www.google.com/jsapi"></script><script type="text/javascript">google.load("elements", "1", {packages: "transliteration"});</script><script type="text/javascript" src="http://www.google.com/coop/cse/t13n?form=cse-search-box&t13n_langs=en"></script><script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse-search-box&lang=en"></script></tr></table></div></address></body>