代碼出自Qt Creator 快速入門,這裡只是做個記載
mysax.h
#ifndef MYSAX_H#define MYSAX_H#include <QXmlDefaultHandler>class QListWidget;class MySAX : public QXmlDefaultHandler{public: MySAX(); ~MySAX(); bool readFile(const QString &fileName);protected: bool startElement(const QString &namespaceURI, const QString &localName, const QString &qName, const QXmlAttributes &atts); bool endElement(const QString &namespaceURI, const QString &localName, const QString &qName); bool characters(const QString &ch); bool fatalError(const QXmlParseException &exception);private: QListWidget *list; QString currentText;};#endif // MYSAX_H
mysax.cpp
#include "mysax.h"#include <QtXml>#include <QListWidget>MySAX::MySAX(){ list = new QListWidget; list->show();}MySAX::~MySAX(){ delete list;}bool MySAX::readFile(const QString &fileName){ QFile file(fileName); // 讀取檔案內容 QXmlInputSource inputSource(&file); // 建立QXmlSimpleReader對象 QXmlSimpleReader reader; // 設定內容處理器 reader.setContentHandler(this); // 設定錯誤處理器 reader.setErrorHandler(this); // 解析檔案 return reader.parse(inputSource);}// 已經解析完一個元素的起始標籤bool MySAX::startElement(const QString &namespaceURI, const QString &localName, const QString &qName, const QXmlAttributes &atts){ if (qName == "library") list->addItem(qName); else if (qName == "book") list->addItem(" " + qName + atts.value("id")); return true;}// 已經解析完一塊字元資料bool MySAX::characters(const QString &ch){ currentText = ch; return true;}// 已經解析完一個元素的結束標籤bool MySAX::endElement(const QString &namespaceURI, const QString &localName, const QString &qName){ if (qName == "title" || qName == "author") list->addItem(" " + qName + " : " + currentText); return true;}// 錯誤處理bool MySAX::fatalError(const QXmlParseException &exception){ qDebug() << exception.message(); return false;}
main.cpp
#include "mysax.h"#include <QApplication>int main(int argc, char* argv[]){ QApplication app(argc, argv); MySAX sax; sax.readFile("../mySAX/my.xml"); return app.exec();}