解析XML文件及QTableWidget示例
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QtXml>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowTitle("解析XML文件示例");
ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui->tableWidget->setSelectionBehavior(QTableWidget::SelectRows);
ui->tableWidget->setSelectionMode(QTableWidget::SingleSelection);
ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->pushButton->setEnabled(true);
ui->pushButton_2->setEnabled(false);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::Parser(QString path)
{
ui->tableWidget->setRowCount(0);
QFile file(path);
file.open(QIODevice::ReadWrite | QIODevice::Text);
QDomDocument doc;
doc.setContent(&file);
QDomElement root = doc.documentElement();
for(int i=0; i<root.childNodes().count(); i++)
{
ui->tableWidget->setRowCount(ui->tableWidget->rowCount() + 1);
QDomNodeList list = root.childNodes().at(i).childNodes();
for(int j=0; j<list.count(); j++)
{
QDomElement element = list.at(j).toElement();
ui->tableWidget->setItem(i, j, new QTableWidgetItem(element.text()));
}
// QDomElement e=doc.createElement("taglib-website");
// auto text=doc.createTextNode("http://www.xieyincai.com");
// e.appendChild(text);
// root.childNodes().at(i).appendChild(e);
}
//输出到文件
QTextStream out_stream(&file);
doc.save(out_stream,4); //缩进4格
file.close();
}
void MainWindow::on_pushButton_clicked()
{
Parser("web.xml");
ui->pushButton->setEnabled(false);
ui->pushButton_2->setEnabled(true);
}
void MainWindow::on_pushButton_2_clicked()
{
ui->tableWidget->setRowCount(0);
ui->pushButton->setEnabled(true);
ui->pushButton_2->setEnabled(false);
}
void MainWindow::on_pushButton_3_clicked()
{
close();
}
解析XML文件及QTableWidget示例