1 #include <QtGui> 2 #include <QtXml> 3 #include <iostream> 4 5 //创建一个树结构 6 void populateTree(QTreeWidget *treeWidget) 7 { 8 QStringList labels; 9 labels << QObject::tr("Terms") << QObject::tr("Pages"); 10 11 treeWidget->setHeaderLabels(labels); 12 treeWidget->header()->setResizeMode(QHeaderView::Stretch); 13 treeWidget->setWindowTitle(QObject::tr("XML Stream Writer")); 14 treeWidget->show(); 15 16 (void) new QTreeWidgetItem(treeWidget, 17 QStringList() << "sidebearings" << "10, 34-35, 307-308"); 18 QTreeWidgetItem *subterm = new QTreeWidgetItem(treeWidget, 19 QStringList() << "subtraction"); 20 (void) new QTreeWidgetItem(subterm, 21 QStringList() << "of pictures" << "115, 244"); 22 (void) new QTreeWidgetItem(subterm, 23 QStringList() << "of vectors" << "9"); 24 } 25 26 //生成一个新的开始标签 27 void writeIndexEntry(QXmlStreamWriter *xmlWriter, QTreeWidgetItem *item) 28 { 29 //创建一个开始标签 30 xmlWriter->writeStartElement("entry"); 31 //给标签添加属性 32 xmlWriter->writeAttribute("term", item->text(0)); 33 //获取子树的第二个元素 34 QString pageString = item->text(1); 35 //根据','拆开 36 if (!pageString.isEmpty()) { 37 QStringList pages = pageString.split(", "); 38 //依次写入Text元素 39 foreach (QString page, pages) 40 xmlWriter->writeTextElement("page", page); 41 } 42 //如果有子项则递归调用 43 for (int i = 0; i < item->childCount(); ++i) 44 writeIndexEntry(xmlWriter, item->child(i)); 45 xmlWriter->writeEndElement(); 46 } 47 48 49 bool writeXml(const QString &fileName, QTreeWidget *treeWidget) 50 { 51 QFile file(fileName); 52 if (!file.open(QFile::WriteOnly | QFile::Text)) { 53 std::cerr << "Error: Cannot write file " 54 << qPrintable(fileName) << ": " 55 << qPrintable(file.errorString()) << std::endl; 56 return false; 57 } 58 59 //写xml 60 QXmlStreamWriter xmlWriter(&file); 61 xmlWriter.setAutoFormatting(true); 62 //写首行<?xml version="1.0" encoding="UTF-8"> 63 xmlWriter.writeStartDocument(); 64 //生成一个开始标签 65 xmlWriter.writeStartElement("bookindex"); 66 //对于每一个顶级项,调用writeIndexEntry函数 67 for (int i = 0; i < treeWidget->topLevelItemCount(); ++i) 68 writeIndexEntry(&xmlWriter, treeWidget->topLevelItem(i)); 69 xmlWriter.writeEndDocument(); 70 71 file.close(); 72 if (file.error()) { 73 std::cerr << "Error: Cannot write file " 74 << qPrintable(fileName) << ": " 75 << qPrintable(file.errorString()) << std::endl; 76 return false; 77 } 78 return true; 79 } 80 81 int main(int argc, char *argv[]) 82 { 83 QApplication app(argc, argv); 84 QTreeWidget treeWidget; 85 populateTree(&treeWidget); 86 writeXml("out1.xml", &treeWidget); 87 return app.exec(); 88 }