Qt: QXMLStreamReader,读XML文件实例

前端之家收集整理的这篇文章主要介绍了Qt: QXMLStreamReader,读XML文件实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

主要接口:

1、TokenType@H_301_4@ QXmlStreamReader::@H_301_4@readNext@H_301_4@()@H_301_4@

功能:读取下一个标记,并返回其类型。@H_301_4@

主要的类型有:@H_301_4@

@H_301_4@

e@H_301_4@num QXmlStreamReader::@H_301_4@TokenType@H_301_4@

This enum specifies the type of token the reader just read.


Constant@H_301_4@

Value@H_301_4@

Description@H_301_4@

QXmlStreamReader::NoToken@H_301_4@

0@H_301_4@

The reader has not yet read anything.

QXmlStreamReader::Invalid@H_301_4@

1@H_301_4@

An error has occurred,reported in error() and errorString().

QXmlStreamReader::StartDocument@H_301_4@

2@H_301_4@

The reader reports the XML version number in documentVersion(),and the encoding as specified in the XML document in documentEncoding(). If the document is declared standalone,isStandaloneDocument() returns true@H_301_4@; otherwise it returns false@H_301_4@.

QXmlStreamReader::EndDocument@H_301_4@

3@H_301_4@

The reader reports the end of the document.

QXmlStreamReader::StartElement@H_301_4@

4@H_301_4@

The reader reports the start of an element with namespaceUri() and name(). Empty elements are also reported as StartElement,followed directly by EndElement. The convenience function readElementText() can be called to concatenate all content until the corresponding EndElement. Attributes are reported in attributes(),namespace declarations in namespaceDeclarations().

QXmlStreamReader::EndElement@H_301_4@

5@H_301_4@

The reader reports the end of an element with namespaceUri() and name().

QXmlStreamReader::Characters@H_301_4@

6@H_301_4@

The reader reports characters in text(). If the characters are all white-space,isWhitespace() returns true@H_301_4@. If the characters stem from a CDATA section,isCDATA() returns true@H_301_4@.

QXmlStreamReader::Comment@H_301_4@

7@H_301_4@

The reader reports a comment in text().

QXmlStreamReader::DTD@H_301_4@

8@H_301_4@

The reader reports a DTD in text(),notation declarations in notationDeclarations(),and entity declarations in entityDeclarations(). Details of the DTD declaration are reported in in dtdName(),dtdPublicId(),and dtdSystemId().

QXmlStreamReader::EntityReference@H_301_4@

9@H_301_4@

The reader reports an entity reference that could not be resolved. The name of the reference is reported in name(),the replacement text in text().

QXmlStreamReader::ProcessingInstruction@H_301_4@

10@H_301_4@

The reader reports a processing instruction in @L_502_27@() and processingInstructionData().


2、b@H_301_4@ool@H_301_4@ QXmlStreamReader::@H_301_4@atEnd@H_301_4@() const@H_301_4@

功能:判断是否已经读到XML文件的末尾,如果是,则返回true,否则返回false.@H_301_4@


@H_301_4@

3、QXmlStreamAttributes@H_301_4@ QXmlStreamReader::@H_301_4@attributes@H_301_4@() const@H_301_4@@H_301_4@@H_301_4@

功能:返回StartElement.的属性。@H_301_4@@H_301_4@

4、QStringRef@H_301_4@ QXmlStreamReader::@H_301_4@name@H_301_4@() const@H_301_4@@H_301_4@@H_301_4@

功能:返回StartElement,EndElement名称
@H_301_4@@H_301_4@@H_301_4@@H_301_4@

5、v@H_301_4@oid@H_301_4@ QXmlStreamReader::@H_301_4@raiseError@H_301_4@(const @H_301_4@QString &@H_301_4@message@H_301_4@ = QString())@H_301_4@@H_301_4@@H_301_4@@H_301_4@@H_301_4@

功能:提出一个错误,@H_301_4@@H_301_4@@H_301_4@@H_301_4@@H_301_4@


需求:

使用QXMLStreamReader,读取XML文件,并使用XML文件初始化树形控件。@H_301_4@


效果图:



源码:

main.cpp

#include <QApplication>
#include <QTreeWidget>
#include <QLabel>
#include <QHeaderView>
#include <QObject>
#include "xmlstreamreader.h"

int main(int argc,char *argv[])
{
    QApplication a(argc,argv);

    QTreeWidget *tree = new QTreeWidget;
    tree->setHeaderLabels( QStringList()<<"Term"<<"Pages"<<"Description" );
    tree->header()->setSectionResizeMode(QHeaderView::Stretch);
    tree->setWindowTitle(QObject::tr("XML Reader"));
    tree->show();

    QString fileName("in1.xml");
    XMLStreamReader w(tree);
    w.readFile(fileName);

    return a.exec();
}

XMLStreamReader.h

#ifndef XMLSTREAMREADER_H
#define XMLSTREAMREADER_H

#include <QXmlStreamReader>
#include <QTreeWidget>
#include <QTreeWidgetItem>

class XMLStreamReader
{

public:
    XMLStreamReader(QTreeWidget *tree);
    ~XMLStreamReader();
    bool readFile(const QString &fileName);

private:
    void readBookindexElement();
    void readEntryElement(QTreeWidgetItem *parent);
    void readPageElement(QTreeWidgetItem *parent);
    void skipUnknownElement();

    QTreeWidget *treeWidget;
    QXmlStreamReader reader;
};

#endif // XMLSTREAMREADER_H


XMLStreamReader.cpp

#include <QFile>
#include <QDebug>
#include "xmlstreamreader.h"

XMLStreamReader::XMLStreamReader(QTreeWidget *tree)
{
    treeWidget = tree;
}

XMLStreamReader::~XMLStreamReader()
{
    delete treeWidget;
}

bool XMLStreamReader::readFile(const QString &fileName)
{
    QFile file(fileName);
    if(!file.open(QFile::ReadOnly | QFile::Text))
    {
        qDebug()<<"Open XML file Error";
        return false;
    }

    reader.setDevice(&file);
    while(!reader.atEnd())
    {
        if(reader.isStartElement())
        {
            if(reader.name() == "bookindex")
            {
                readBookindexElement();
            }
            else
            {
                Q_ASSERT(reader.isStartElement() && (reader.name() == "bookindex")); //断言
                reader.raiseError(QObject::tr("Not a BookIndex file"));
            }
        }
        else
        {
            reader.readNext();
        }
    }

    file.close();
    if(reader.hasError())
    {
        qDebug()<<reader.errorString();
        return false;
    }
    else if(file.error() != QFile::NoError)
    {
        qDebug()<<file.errorString();
        return false;
    }

    return true;
}

void XMLStreamReader::readBookindexElement()
{
    reader.readNext();
    while(!reader.atEnd())
    {
        if(reader.isEndElement())
        {
            reader.readNext();
            break;
        }

        if(reader.isStartElement())
        {
            if(reader.name() == "entry")
            {
                readEntryElement(treeWidget->invisibleRootItem());
            }
            else
            {
                skipUnknownElement();
            }
        }
        else
        {
            reader.readNext();
        }
    }
}

void XMLStreamReader::readEntryElement(QTreeWidgetItem *parent)
{
    QTreeWidgetItem *item = new QTreeWidgetItem(parent);
    item->setText(0,reader.attributes().value("term").toString());
    item->setText(2,reader.attributes().value("description").toString());
    reader.readNext();
    while(!reader.atEnd())
    {
        if(reader.isEndElement())
        {
            reader.readNext();
            break;
        }

        if(reader.isStartElement())
        {
            if(reader.name() == "entry")
            {
                readEntryElement(item);
            }
            else if(reader.name() == "page")
            {
                readPageElement(item);
            }
        }
        else
        {
            reader.readNext();
        }
    }
}

void XMLStreamReader::readPageElement(QTreeWidgetItem *parent)
{
    QString page = reader.readElementText();
    if(reader.isEndElement())
        reader.readNext();

    QString allPages = parent->text(1);
    if(!allPages.isEmpty())
        allPages +=",";
    allPages += page;
    parent->setText(1,allPages);
}

void XMLStreamReader::skipUnknownElement()
{
    reader.readNext();
    while(!reader.atEnd())
    {
        if(reader.isEndElement())
        {
            reader.readNext();
            break;
        }

        if(reader.isStartElement())
        {
            skipUnknownElement();
        }
        else
        {
            reader.readNext();
        }
    }
}

猜你在找的XML相关文章