XML 解析之SAX

前端之家收集整理的这篇文章主要介绍了XML 解析之SAX前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

代码出自Qt Creator 快速入门,这里只是做个记载

xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <library>
  3. <book id="01">
  4. <title>Qt</title>
  5. <author>shiming</author>
  6. </book>
  7. <book id="02">
  8. <title>linux</title>
  9. <author>shiming</author>
  10. </book>
  11. </library>


mysax.h

  1. #ifndef MYSAX_H
  2. #define MYSAX_H
  3.  
  4. #include <QXmlDefaultHandler>
  5. class QListWidget;
  6.  
  7. class MySAX : public QXmlDefaultHandler
  8. {
  9. public:
  10. MySAX();
  11. ~MySAX();
  12. bool readFile(const QString &fileName);
  13. protected:
  14. bool startElement(const QString &namespaceURI,const QString &localName,const QString &qName,const QXmlAttributes &atts);
  15. bool endElement(const QString &namespaceURI,const QString &qName);
  16. bool characters(const QString &ch);
  17. bool fatalError(const QXmlParseException &exception);
  18.  
  19. private:
  20. QListWidget *list;
  21. QString currentText;
  22. };
  23.  
  24. #endif // MYSAX_H


mysax.cpp

  1. #include "mysax.h"
  2. #include <QtXml>
  3. #include <QListWidget>
  4.  
  5. MySAX::MySAX()
  6. {
  7. list = new QListWidget;
  8. list->show();
  9. }
  10.  
  11. MySAX::~MySAX()
  12. {
  13. delete list;
  14. }
  15.  
  16. bool MySAX::readFile(const QString &fileName)
  17. {
  18. QFile file(fileName);
  19. // 读取文件内容
  20. QXmlInputSource inputSource(&file);
  21. // 建立QXmlSimpleReader对象
  22. QXmlSimpleReader reader;
  23. // 设置内容处理器
  24. reader.setContentHandler(this);
  25. // 设置错误处理器
  26. reader.setErrorHandler(this);
  27. // 解析文件
  28. return reader.parse(inputSource);
  29. }
  30.  
  31. // 已经解析完一个元素的起始标签
  32. bool MySAX::startElement(const QString &namespaceURI,const QXmlAttributes &atts)
  33. {
  34. if (qName == "library")
  35. list->addItem(qName);
  36. else if (qName == "book")
  37. list->addItem(" " + qName + atts.value("id"));
  38. return true;
  39. }
  40.  
  41. // 已经解析完一块字符数据
  42. bool MySAX::characters(const QString &ch)
  43. {
  44. currentText = ch;
  45. return true;
  46. }
  47.  
  48. // 已经解析完一个元素的结束标签
  49. bool MySAX::endElement(const QString &namespaceURI,const QString &qName)
  50. {
  51. if (qName == "title" || qName == "author")
  52. list->addItem(" " + qName + " : " + currentText);
  53. return true;
  54. }
  55.  
  56. // 错误处理
  57. bool MySAX::fatalError(const QXmlParseException &exception)
  58. {
  59. qDebug() << exception.message();
  60. return false;
  61. }


main.cpp

  1. #include "mysax.h"
  2. #include <QApplication>
  3.  
  4. int main(int argc,char* argv[])
  5. {
  6. QApplication app(argc,argv);
  7. MySAX sax;
  8. sax.readFile("../mySAX/my.xml");
  9. return app.exec();
  10. }

猜你在找的XML相关文章