Exemplo n.º 1
0
void TestLanguageFiles::languageSchemeValidationTest()
{
    QUrl languageFile = QUrl::fromLocalFile("schemes/language.xsd");
    QXmlSchema languageSchema;
    QVERIFY(languageSchema.load(languageFile));
    QVERIFY(languageSchema.isValid());
}
Exemplo n.º 2
0
Arquivo: xml.cpp Projeto: karban/field
ErrorResult validateXML(const QString &fileName, const QString &schemaFileName)
{
    QXmlSchema schema;
    schema.load(QUrl(schemaFileName));

    MessageHandler schemaMessageHandler;
    schema.setMessageHandler(&schemaMessageHandler);

    if (!schema.isValid())
        return ErrorResult(ErrorResultType_Critical, QObject::tr("Schena '%1' is not valid. %2").
                           arg(schemaFileName).
                           arg(schemaMessageHandler.statusMessage()));

    QFile file(fileName);
    file.open(QIODevice::ReadOnly);

    QXmlSchemaValidator validator(schema);
    MessageHandler validatorMessageHandler;
    validator.setMessageHandler(&validatorMessageHandler);

    //TODO neslo mi nacist soubor se dvema poli
//    if (!validator.validate(&file, QUrl::fromLocalFile(file.fileName())))
//        return ErrorResult(ErrorResultType_Critical, QObject::tr("File '%1' is not valid Agros2D problem file. Error (line %3, column %4): %2").
//                           arg(fileName).
//                           arg(validatorMessageHandler.statusMessage()).
//                           arg(validatorMessageHandler.line()).
//                           arg(validatorMessageHandler.column()));

    return ErrorResult();
}
//! [3]
void MainWindow::validate()
{
    const QByteArray schemaData = schemaView->toPlainText().toUtf8();
    const QByteArray instanceData = instanceEdit->toPlainText().toUtf8();

    MessageHandler messageHandler;

    QXmlSchema schema;
    schema.setMessageHandler(&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->setText(messageHandler.statusMessage());
        moveCursor(messageHandler.line(), messageHandler.column());
    } else {
        validationStatus->setText(tr("validation successful"));
    }

    const QString styleSheet = QString("QLabel {background: %1; padding: 3px}")
                                      .arg(errorOccurred ? QColor(Qt::red).lighter(160).name() :
                                                           QColor(Qt::green).lighter(160).name());
    validationStatus->setStyleSheet(styleSheet);
}
Exemplo n.º 4
0
void tst_QXmlSchema::copyConstructor() const
{
    /* Verify that we can take a const reference, and simply do a copy of a default constructed object. */
    {
        const QXmlSchema schema1;
        QXmlSchema schema2(schema1);
    }

    /* Copy twice. */
    {
        const QXmlSchema schema1;
        QXmlSchema schema2(schema1);
        QXmlSchema schema3(schema2);
    }

    /* Verify that copying default values works. */
    {
        const QXmlSchema schema1;
        const QXmlSchema schema2(schema1);
        QCOMPARE(schema2.messageHandler(), schema1.messageHandler());
        QCOMPARE(schema2.uriResolver(), schema1.uriResolver());
        QCOMPARE(schema2.networkAccessManager(), schema1.networkAccessManager());
        QCOMPARE(schema2.isValid(), schema1.isValid());
    }
}
Exemplo n.º 5
0
static bool initMusicXmlSchema(QXmlSchema& schema)
      {
      // read the MusicXML schema from the application resources
      QFile schemaFile(":/schema/musicxml.xsd");
      if (!schemaFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
            qDebug("initMusicXmlSchema() could not open resource musicxml.xsd");
            MScore::lastError = QObject::tr("Internal error: Could not open resource musicxml.xsd\n");
            return false;
            }

      // copy the schema into a QByteArray and fixup xs:imports,
      // using a path to the application resources instead of to www.musicxml.org
      // to prevent downloading from the net
      QByteArray schemaBa;
      QTextStream schemaStream(&schemaFile);
      while (!schemaStream.atEnd()) {
            QString line = schemaStream.readLine();
            if (line.contains("xs:import"))
                  line.replace("http://www.musicxml.org/xsd", "qrc:///schema");
            schemaBa += line.toUtf8();
            schemaBa += "\n";
            }

      // load and validate the schema
      schema.load(schemaBa);
      if (!schema.isValid()) {
            qDebug("initMusicXmlSchema() internal error: MusicXML schema is invalid");
            MScore::lastError = QObject::tr("Internal error: MusicXML schema is invalid\n");
            return false;
            }

      return true;
      }
Exemplo n.º 6
0
int XMLQtInterface::isValid() const
{
	QXmlSchema schema;
	if(_schemaName.length() > 0)
		schema.load( QUrl::fromLocalFile((QString::fromStdString(_schemaName))) );

	if ( schema.isValid() )
	{
		QXmlSchemaValidator validator( schema );
		if ( validator.validate( _fileData ) )
			return 1;
		else
		{
			INFO("XMLQtInterface::isValid(): XML file %s is invalid (in reference to schema %s).",
			     _fileName.toStdString().c_str(), _schemaName.c_str());
		}
	}
	else
	{
		// The following validator (without constructor arguments) automatically
		// searches for the xsd given in the xml file.
		QXmlSchemaValidator validator;
		if ( validator.validate( _fileData ) )
			return 1;
		else
		{
			INFO("XMLQtInterface::isValid(): XML file %s is invalid (in reference to its schema).",
			     _fileName.toStdString().c_str());
		}
	}
	return 0;
}
Exemplo n.º 7
0
bool PairsTheme::isValid(const KArchiveFile* file) {

    KUrl schemaUrl = KUrl::fromLocalFile(KGlobal::dirs()->findResource("appdata", QLatin1String( "themes/game.xsd" )));
    QXmlSchema schema;
    schema.load(schemaUrl);

    if(!schema.isValid()) {
        qWarning() << "game Schema not valid";
        return false;
    }
    QXmlSchemaValidator validator(schema);
    return validator.validate(file->data());
}
Exemplo n.º 8
0
void Fenetre::ouvrir()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Séléctionner un fichier"),
                                                    QDir::currentPath(),
                                                    tr("Fichiers XML (*.xml)"));
    if (fileName.isEmpty())
        return;

    QFile fileXML(fileName);
    if (!fileXML.open(QFile::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("Erreur lecture"),
                             tr("Impossible de lire le fichier %1:\n%2.")
                             .arg(fileName)
                             .arg(fileXML.errorString()));
        return;
    }

    QFile fileSchema("schemaGraph.xsd");
    fileSchema.open(QIODevice::ReadOnly);

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

    schema.load(&fileSchema, QUrl::fromLocalFile(fileSchema.fileName()));
    if (schema.isValid()) {
        QFile fileXML2(fileName);
        fileXML2.open(QIODevice::ReadOnly);

        QXmlSchemaValidator validator(schema);
        if (!validator.validate(&fileXML2, QUrl::fromLocalFile(fileXML2.fileName()))){
            QMessageBox::warning(this, tr("Fichier malformé"),
                                 tr("Impossible d'ouvrir le fichier' %1'.\n Le document ne correspond pas au schéma. \n%2")
                                 .arg(fileName)
                                 .arg(messageHandler.statusMessage()));
            return;
        }
    }

    ImportExport import=ImportExport(&graphe,xmltree, affichageSVG);
    if (import.ouvrir(&fileXML, &domDocument))
        ui->statusBar->showMessage(tr("Fichier chargé"), 2000);

    affichageSVG->drawGraph();
    ui->afficheGraphe->adjustSize();

    //On pense à remettre la liste des sommets pour créer les arcs
    redessinerComboArc();
}
Exemplo n.º 9
0
Arquivo: main.cpp Projeto: maxxant/qt
void Schema::loadFromFile() const
{
//! [1]
    QFile file("myschema.xsd");
    file.open(QIODevice::ReadOnly);

    QXmlSchema schema;
    schema.load(&file, QUrl::fromLocalFile(file.fileName()));

    if (schema.isValid())
        qDebug() << "schema is valid";
    else
        qDebug() << "schema is invalid";
//! [1]
}
Exemplo n.º 10
0
QObject * LanguageResource::resource()
{
    if (d->m_languageResource != 0) {
        return d->m_languageResource;
    }

    if (!d->m_path.isLocalFile()) {
        qWarning() << "Cannot open language file at " << d->m_path.toLocalFile() << ", aborting.";
        return 0;
    }

    QXmlSchema schema = loadXmlSchema("language");
    if (!schema.isValid()) {
        return 0;
    }

    QDomDocument document = loadDomDocument(d->m_path, schema);
    if (document.isNull()) {
        qWarning() << "Could not parse document " << d->m_path.toLocalFile() << ", aborting.";
        return 0;
    }

    QDomElement root(document.documentElement());
    d->m_languageResource = new Language(this);
    d->m_languageResource->setFile(d->m_path);
    d->m_languageResource->setId(root.firstChildElement("id").text());
    d->m_languageResource->setTitle(root.firstChildElement("title").text());
    d->m_languageResource->seti18nTitle(root.firstChildElement("i18nTitle").text());
    // create phoneme groups
    for (QDomElement groupNode = root.firstChildElement("phonemeGroups").firstChildElement();
         !groupNode.isNull();
         groupNode = groupNode.nextSiblingElement())
    {
        PhonemeGroup *group = d->m_languageResource->addPhonemeGroup(
            groupNode.firstChildElement("id").text(),
            groupNode.firstChildElement("title").text());
        group->setDescription(groupNode.attribute("description"));
        // register phonemes
        for (QDomElement phonemeNode = groupNode.firstChildElement("phonemes").firstChildElement();
            !phonemeNode.isNull();
            phonemeNode = phonemeNode.nextSiblingElement())
        {
            group->addPhoneme(phonemeNode.firstChildElement("id").text(), phonemeNode.firstChildElement("title").text());
        }
    }

    return d->m_languageResource;
}
MerDevicesXmlReader::MerDevicesXmlReader(const QString &fileName, QObject *parent)
    : QObject(parent),
      d(new MerDevicesXmlReaderPrivate)
{
    Utils::FileReader reader;
    d->error = !reader.fetch(fileName, QIODevice::ReadOnly);
    if (d->error) {
        d->errorString = reader.errorString();
        return;
    }

    QXmlSchema schema;
    schema.setMessageHandler(&d->messageHandler);

    Utils::FileReader schemeReader;
    d->error = !schemeReader.fetch(QString::fromLatin1("%1/mer/devices.xsd").arg(sharedDirPath()),
            QIODevice::ReadOnly);
    if (d->error) {
        d->errorString = schemeReader.errorString();
        return;
    }
    schema.load(schemeReader.data());
    d->error = !schema.isValid();
    if (d->error) {
        d->errorString = d->messageHandler.errorString();
        return;
    }

    QXmlSchemaValidator validator(schema);
    validator.setMessageHandler(&d->messageHandler);
    d->error = !validator.validate(reader.data());
    if (d->error) {
        d->errorString = d->messageHandler.errorString();
        return;
    }

    d->query.setQuery(QString::fromLatin1("doc('%1')").arg(fileName));
    d->query.setMessageHandler(&d->messageHandler);
    d->error = !d->query.isValid();
    if (d->error) {
        d->errorString = d->messageHandler.errorString();
        return;
    }

    d->error = !d->query.evaluateTo(d->receiver);
    if (d->error)
        d->errorString = d->messageHandler.errorString();
}
Exemplo n.º 12
0
void cActionDefList::validateActionDef( const QString &p_qsActionDefFile, const QString &p_qsSchemaFile ) throw( cSevException )
{
    cTracer  obTracer( &g_obLogger, "cActionList::validateActionDef", p_qsActionDefFile.toStdString() );

    QFile obActionsFile( p_qsActionDefFile );

    try
    {
        if( !obActionsFile.open( QIODevice::ReadOnly ) )
        {
            throw cSevException( cSeverity::ERROR, QString( "Cannot open Actions file: %1" ).arg( p_qsActionDefFile ).toStdString() );
        }

        QXmlSchema obSchema;
        obSchema.load( p_qsSchemaFile );

        if( !obSchema.isValid() )
        {
            throw cSevException( cSeverity::ERROR, QString( "Schema %1 is not valid" ).arg( p_qsSchemaFile ).toStdString() );
        }

        QXmlSchemaValidator obValidator( obSchema );
        if( !obValidator.validate( &obActionsFile, QUrl::fromLocalFile( p_qsActionDefFile ) ) )
        {
            throw cSevException( cSeverity::ERROR,
                                 QString( "Action definition file %1 is not valid according to Schema %2" ).arg( p_qsActionDefFile ).arg( p_qsSchemaFile ).toStdString() );
        }

        QString      qsErrorMsg  = "";
        int          inErrorLine = 0;
        obActionsFile.seek( 0 );
        if( !m_poActionsDoc->setContent( &obActionsFile, &qsErrorMsg, &inErrorLine ) )
        {
            throw cSevException( cSeverity::ERROR,
                                 QString( "Parsing Actions file: %1 - Error in line %2: %3" ).arg( p_qsActionDefFile ).arg( inErrorLine ).arg( qsErrorMsg ).toStdString() );
        }

        obActionsFile.close();
    }
    catch( cSevException &e )
    {
        obActionsFile.close();

        throw e;
    }
}
Exemplo n.º 13
0
/*!
 * \brief Utilities::parseMetaModelText
 * Parses the MetaModel text against the schema.
 * \param pMessageHandler
 * \param contents
 */
void Utilities::parseMetaModelText(MessageHandler *pMessageHandler, QString contents)
{
  QFile schemaFile(QString(":/Resources/XMLSchema/tlmModelDescription.xsd"));
  schemaFile.open(QIODevice::ReadOnly);
  const QString schemaText(QString::fromUtf8(schemaFile.readAll()));
  schemaFile.close();
  const QByteArray schemaData = schemaText.toUtf8();

  QXmlSchema schema;
  schema.setMessageHandler(pMessageHandler);
  schema.load(schemaData);
  if (!schema.isValid()) {
    pMessageHandler->setFailed(true);
  } else {
    QXmlSchemaValidator validator(schema);
    if (!validator.validate(contents.toUtf8())) {
      pMessageHandler->setFailed(true);
    }
  }
}
Exemplo n.º 14
0
Arquivo: main.cpp Projeto: maxxant/qt
void Schema::loadFromData() const
{
//! [2]
    QByteArray data( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                     "<xsd:schema"
                     "        xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
                     "        xmlns=\"http://qt.nokia.com/xmlschematest\""
                     "        targetNamespace=\"http://qt.nokia.com/xmlschematest\""
                     "        version=\"1.0\""
                     "        elementFormDefault=\"qualified\">"
                     "</xsd:schema>" );

    QXmlSchema schema;
    schema.load(data);

    if (schema.isValid())
        qDebug() << "schema is valid";
    else
        qDebug() << "schema is invalid";
//! [2]
}
Exemplo n.º 15
0
void XSDTSTestCase::executeSchemaTest(TestResult::Status &resultStatus, QString &serialized, QAbstractMessageHandler *handler)
{
    QFile file(m_schemaUri.path());
    if (!file.open(QIODevice::ReadOnly)) {
        resultStatus = TestResult::Fail;
        serialized = QString();
        return;
    }

    QXmlSchema schema;
    schema.setMessageHandler(handler);
    schema.load(&file, m_schemaUri);

    if (schema.isValid()) {
        resultStatus = TestResult::Pass;
        serialized = QString::fromLatin1("true");
    } else {
        resultStatus = TestResult::Pass;
        serialized = QString::fromLatin1("false");
    }
}
Exemplo n.º 16
0
void XSDTSTestCase::executeInstanceTest(TestResult::Status &resultStatus, QString &serialized, QAbstractMessageHandler *handler)
{
    QFile instanceFile(m_instanceUri.path());
    if (!instanceFile.open(QIODevice::ReadOnly)) {
        resultStatus = TestResult::Fail;
        serialized = QString();
        return;
    }

    QXmlSchema schema;
    if (m_schemaUri.isValid()) {
        QFile file(m_schemaUri.path());
        if (!file.open(QIODevice::ReadOnly)) {
            resultStatus = TestResult::Fail;
            serialized = QString();
            return;
        }

        schema.setMessageHandler(handler);
        schema.load(&file, m_schemaUri);

        if (!schema.isValid()) {
            resultStatus = TestResult::Pass;
            serialized = QString::fromLatin1("false");
            return;
        }
    }

    QXmlSchemaValidator validator(schema);
    validator.setMessageHandler(handler);

    qDebug("check %s", qPrintable(m_instanceUri.path()));
    if (validator.validate(&instanceFile, m_instanceUri)) {
        resultStatus = TestResult::Pass;
        serialized = QString::fromLatin1("true");
    } else {
        resultStatus = TestResult::Pass;
        serialized = QString::fromLatin1("false");
    }
}
Exemplo n.º 17
0
void TestLanguageFiles::checkIdUniqueness()
{
    ResourceManager manager;
    QStringList languageFiles = QStandardPaths::locateAll(QStandardPaths::DataLocation, QString("data/languages/*.xml"));
    foreach (const QString &file, languageFiles) {
        qDebug() << "File being parsed: " << file;
        QStringList idList;
        const QUrl &languageFile = QUrl::fromLocalFile(file);
        QVERIFY(languageFile.isLocalFile());

        QXmlSchema schema = loadXmlSchema("language");
        QVERIFY(schema.isValid());

        QDomDocument document = loadDomDocument(languageFile, schema);
        QVERIFY(!document.isNull());

        QDomElement root(document.documentElement());
        Language *language = new Language(this);
        language->setFile(languageFile);
        language->setId(root.firstChildElement("id").text());
        language->setTitle(root.firstChildElement("title").text());
        // create phoneme groups
        for (QDomElement groupNode = root.firstChildElement("phonemeGroups").firstChildElement();
                !groupNode.isNull();
                groupNode = groupNode.nextSiblingElement())
        {
            for (QDomElement phonemeNode = groupNode.firstChildElement("phonemes").firstChildElement();
                    !phonemeNode.isNull();
                    phonemeNode = phonemeNode.nextSiblingElement())
            {
                QString id = phonemeNode.firstChildElement("id").text();
                qDebug() << "ID: " << id;
                QVERIFY2(!idList.contains(id),"Phoneme ID used more than once in the tested file");
                idList.append(id);
            }
        }
    }
Exemplo n.º 18
0
FileReader::FileReader(QString fileName, QAbstractItemModel* d, MyWidget* p) : file(fileName), model(d), parent(p) {
    QByteArray data("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
                    "<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"
                    "<xsd:element name=\"chart\" type=\"chartType\"/>"
                    "	<xsd:complexType name=\"chartType\">"
                    "		<xsd:sequence>"
                    "			<xsd:element name=\"title\" type=\"xsd:string\"/>"
                    "			<xsd:element name=\"xlabel\" type=\"xsd:string\" minOccurs=\"0\"/>"
                    "			<xsd:element name=\"ylabel\" type=\"xsd:string\" minOccurs=\"0\"/>"
                    "			<xsd:element name=\"point\" type=\"pointType\" maxOccurs=\"unbounded\"/>"
                    "		</xsd:sequence>"
                    "	</xsd:complexType>"
                    "	<xsd:complexType name=\"pointType\">"
                    "		<xsd:sequence>"
                    "			<xsd:element name=\"x\" type=\"xsd:string\"/>"
                    "			<xsd:element name=\"y\" type=\"xsd:string\"/>"
                    "		</xsd:sequence>"
                    "	</xsd:complexType>"
                    "</xsd:schema>");
    if(!file.open(QFile::ReadOnly | QFile::Text)) {
        QMessageBox::warning(parent, tr("qCharts"), tr("Cannot read file %1:\n%2.").arg(fileName).arg(file.errorString()));
        return;
    }
    QXmlSchema schema;
    schema.load(data);
    if(schema.isValid()) {
        QXmlSchemaValidator validator(schema);
        if(validator.validate(&file, QUrl::fromLocalFile(file.fileName()))){
            isReadable=true;
        }
        else {
            isReadable=false;
            QMessageBox::warning(this, tr("qCharts"), tr("The file that you are trying to open isn't valid."));
        }
    }
    file.close();
}
Exemplo n.º 19
0
 bool MainWindow::validate()
 {
     QUrl url("qrc:/resources/peach.xsd");

     const QByteArray instanceData = completingTextEdit->toPlainText().toUtf8();

     MessageHandler messageHandler;

     QXmlSchema schema;
     schema.setMessageHandler(&messageHandler);

     schema.load(url);

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

     if (errorOccurred) {
         statusLabel->setText(messageHandler.statusMessage());
         moveCursor(messageHandler.line(), messageHandler.column());
         return false;
     } else {
         statusLabel->setText(tr("Validation successful"));
         return true;
     }

     const QString styleSheet = QString("QstatusLabel {background: %1; padding: 3px}")
                                       .arg(errorOccurred ? QColor(Qt::red).lighter(160).name() :
                                                            QColor(Qt::green).lighter(160).name());
     statusLabel->setStyleSheet(styleSheet);
 }
Exemplo n.º 20
0
bool filePick()
{
    //Read XSD
    file.setFileName("FACTORY.XSD");
    if (!readFile(file.fileName())) return false;

    QXmlSchema schema;
    schema.load(&file);
    if (!schema.isValid())
    {
        QMessageBox::information(NULL, QWidget::tr("XSDRead")
                                 ,QWidget::tr("This is not a valid XSD File!"));
        return false;
    }

    file.close();

    file.setFileName("FACTORY.XML");
    if (!readFile(file.fileName())) return false;

    //DOM Read-In
    QString errorStr;
    int errorLine, errorColumn;
    if (!doc.setContent(&file, true, &errorStr, &errorLine,
                                &errorColumn)) {
        QMessageBox::information(NULL, QWidget::tr("XSDRead"),
                                 QWidget::tr("Parse error at line %1, column %2:\n%3")
                                 .arg(errorLine)
                                 .arg(errorColumn)
                                 .arg(errorStr));
        return false;
    }

    //Reset the file pointer
    file.reset();

    //XSD Validator
    QXmlSchemaValidator validator(schema);
    if (!validator.validate(&file))
    {
        QMessageBox::information(NULL,QWidget::tr("XSDRead"),
                                 QWidget::tr("This is not a valid XML File!"));
        return false;
    }

    //building Treeroot
    QDomElement node = doc.documentElement();
    nodeData* temp = NULL;
    Treeroot = new nodeData;
    Treeroot->name = node.tagName();
    QDomElement child = node.firstChildElement();

    //parsing child elements (if there is)
    while (!child.isNull())
    {
        temp = new nodeData;
        Treeroot->child.append(temp);
        parseElement(temp,child);
        temp->parent = Treeroot;
        child = child.nextSiblingElement();
    }

    return true;
}
Exemplo n.º 21
0
bool BramaZnajomych::wczytajBaze()
{
    QFile plikSchematu(":/znajomi.xsd");
    plikSchematu.open(QIODevice::ReadOnly);
    QXmlSchema schemat;
    schemat.load(&plikSchematu, QUrl::fromLocalFile(plikSchematu.fileName()));

    if(schemat.isValid()){
//        qDebug() << "Schemat Poprawny";
        QString sciezka(katalogBazy);
        sciezka.append("/");
        sciezka.append(login);
        sciezka.append(".xml");
//        qDebug() << sciezka;
        plikBazy = new QFile(sciezka);

        if(plikBazy->open(QIODevice::ReadOnly)){
//            qDebug() << "Plik istnieje";

            QXmlSchemaValidator walidator(schemat);
            if(walidator.validate(plikBazy, QUrl::fromLocalFile(plikBazy->fileName()))){
//                qDebug() << "Plik porawny";

                plikBazy->close();
                plikBazy->open(QIODevice::ReadOnly);

                QDomDocument doc("mydocument");
                if(doc.setContent(plikBazy)){
//                    qDebug() << "Udalo sie zaladowac document";

                } else {
//                    qDebug() << "DomDocument fejl";

                }


                QDomElement glownyElement = doc.documentElement();

                QDomNodeList znajomi = glownyElement.elementsByTagName("znajomy");
                int iloscZnajomych = znajomi.size();

//                qDebug() << "Ilosc znajomych w pliku xml: " << iloscZnajomych;

                for(int i = 0; i < iloscZnajomych; ++i){
                    int id = znajomi.at(i).attributes().namedItem("ID").toAttr().value().toInt();
                    QString nick = znajomi.at(i).attributes().namedItem("login").toAttr().value();
                    listaZnajomych.push_back(qMakePair(nick, id));
                }

            } else{
//                qDebug() << "Poprawnosc pliku xml fejl";
                plikBazy->close();
                zapiszBaze();

            }
        } else {
//            qDebug() << "Plik xml nie istnieje";
            QDir katalog(katalogBazy);
            if(!katalog.exists()){
//                qDebug() << "Katalog bazodanowy nie istnieje";
                if(katalog.mkpath(".")){
//                    qDebug() << "Stworzono katalog bazodanowy";
                } else{
//                    qDebug() << "Proba stworzenia katalogu bazodanowego fejl";

                }
            }
            plikBazy->close();
            zapiszBaze();


        }
    } else {
//        qDebug() << "Schemat fejl";
        return false;

    }

    plikSchematu.close();
    plikBazy->close();


    usunZnajomego(555);

    return true;
}
Exemplo n.º 22
0
void tst_QXmlSchema::isValid() const
{
    /* Check default value. */
    QXmlSchema schema;
    QVERIFY(!schema.isValid());
}
Exemplo n.º 23
0
QT_USE_NAMESPACE

int main(int argc, char **argv)
{
    enum ExitCode
    {
        Valid = 0,
        Invalid,
        ParseError
    };

    enum ExecutionMode
    {
        InvalidMode,
        SchemaOnlyMode,
        InstanceOnlyMode,
        SchemaAndInstanceMode
    };

    const QCoreApplication app(argc, argv);
    QCoreApplication::setApplicationName(QLatin1String("xmlpatternsvalidator"));

    QStringList arguments = QCoreApplication::arguments();
    if (arguments.size() != 2 && arguments.size() != 3) {
        qDebug() << QXmlPatternistCLI::tr("usage: xmlpatternsvalidator (<schema url> | <instance url> <schema url> | <instance url>)");
        return ParseError;
    }

    // parse command line arguments
    ExecutionMode mode = InvalidMode;

    QUrl schemaUri;
    QUrl instanceUri;

    {
        QUrl url = arguments[1];

        if (url.isRelative())
            url = QUrl::fromLocalFile(arguments[1]);

        if (arguments.size() == 2) {
            // either it is a schema or instance document

            if (arguments[1].toLower().endsWith(QLatin1String(".xsd"))) {
                schemaUri = url;
                mode = SchemaOnlyMode;
            } else {
                // as we could validate all types of xml documents, don't check the extension here
                instanceUri = url;
                mode = InstanceOnlyMode;
            }
        } else if (arguments.size() == 3) {
            instanceUri = url;
            schemaUri = arguments[2];

            if (schemaUri.isRelative())
                schemaUri = QUrl::fromLocalFile(schemaUri.toString());

            mode = SchemaAndInstanceMode;
        }
    }

    // Validate schema
    QXmlSchema schema;
    if (InstanceOnlyMode != mode) {
        schema.load(schemaUri);
        if (!schema.isValid())
            return Invalid;
    }

    if (SchemaOnlyMode == mode)
        return Valid;

    // Validate instance
    QXmlSchemaValidator validator(schema);
    if (validator.validate(instanceUri))
        return Valid;

    return Invalid;
}