前言
用Qt中QDomDocument读写Xml格式配置文件,使用时.pro文件中需加
QT += xml
xml格式文件
<manifest package="net.sunniwell.contentprovider" android:versionCode="1" xmlns:android="http://schemas.android.com/apk/res/android" android:versionName="1.0">
<uses-sdk android:targetSdkVersion="21" android:minSdkVersion="8"/>
<application android:allowBackup="true" android:label="@string/app_name" android:theme="@style/AppTheme" android:icon="@drawable/ic_launcher">
<activity android:name="net.sunniwell.contentprovider.test.ui.SWMainActivity">
<intent-filter>
<action android:name="net.sunniwell.contentprovider.UI"/>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name="net.sunniwell.contentprovider.test.ui.SWContactActivity">
<category android:name="android.intent.category.DEFAULT"/>
</activity>
<provider android:name="net.sunniwell.contentprovider.test.SWContentProvider" android:exported="true" android:authorities="net.sunniwell.provider.stb"/>
</application>
</manifest>
读取xml常用方法
QFile file(fileName);
if(!file.open(QIODevice::ReadOnly)){
QMessageBox::warning(nullptr,"提示","文件打开失败!");
return;
}
QDomDocument doc;//doc
QString error;
int row = 0,column = 0 ;
if(!doc.setContent(&file,false,&error,&row,&column)){
QMessageBox::warning(nullptr,"提示","读取xml格式失败!");
return;
}
QDomElement hRoot = doc.documentElement();//获取根节点
QDomNamedNodeMap map = hRoot.attributes();//获取节点中的属性值
for (int j=0; j< map.length(); j++) {
itemTmp->setText(0,map.item(j).nodeName());//获取节点属性名
itemTmp->setText(1,map.item(j).nodeValue());//获取节点属性值
}
QDomNodeList ItemArray = hRoot.childNodes();//获取子节点
for (int i = 0; i<ItemArray.length(); i++) {
QDomElement element = ItemArray.item(i).toElement();//转换为QDomElement获取子节点
//...
//QDomNodeList ItemArray = element .childNodes();//获取子节点
//QDomNamedNodeMap map = element .attributes();//获取节点中的属性值
//...
}
if(hRoot.hasAttribute("name"))//判断是否存在该属性
QString str = hRoot.attribute("name");//根据属性名获取属性值
获取指定节点属性值
//获取指定节点属性值
QFile file(fileName);
if(file.open(QIODevice::ReadOnly)){
QDomDocument doc;//doc
if(doc.setContent(&file)){
QDomElement hRoot = doc.documentElement();//获取根节点
QDomNode n = hRoot.firstChild();//获取第一个子节点
while(!n.isNull()){
QDomElement e=n.toElement();
if(e.nodeName() == "nodeName"){//根据节点名判断
QString value = e.attribute("value");//获取节点中value属性值
break;
}
n = n.nextSibling();//获取下一个兄弟节点
}
}
file.close();
}
保存xml常用方法
QFile file(fileName);
if(!file.open(QIODevice::WriteOnly)){
QMessageBox::warning(nullptr,"提示","文件打开失败!");
return;
}
QDomDocument doc;
QDomElement node = doc.createElement("name");//创建节点名
doc.appendChild(node);//添加到根节点
QDomElement node_1 = doc.createElement("name");//创建节点名
node.appendChild(node_1 );//添加到node节点
node_1.setAttribute("name","value");//添加设置属性名,属性值
QTextStream stream(&file);
doc.save(stream, 4);//保存到文件
file.close();
示例图
示例源码
.h文件文章来源:https://www.toymoban.com/news/detail-699933.html
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTreeWidget>
#include <QDomDocument>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void Read(QDomElement node, QTreeWidgetItem* item);
void Save(QString fileName);
void GetData(QDomDocument doc, QDomElement node, QTreeWidgetItem* item);
private slots:
void OnOpen();
void OnSave();
void OnSaveAs();
private:
Ui::MainWindow *ui;
QTreeWidget* m_treeWidget;
QString m_currentFileName;
};
#endif // MAINWINDOW_H
.cpp文件文章来源地址https://www.toymoban.com/news/detail-699933.html
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QLayout>
#include <QPushButton>
#include <QFileDialog>
#include <QMessageBox>
#include <QDebug>
#include <QHeaderView>
#include <QStyleFactory>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowTitle("XML编辑");
QWidget* widget = new QWidget;
m_treeWidget = new QTreeWidget;
m_treeWidget->setStyle(QStyleFactory::create("windows"));//显示节点虚线 - +
m_treeWidget->setColumnWidth(0, 400);//设置第0列列宽
//m_treeWidget->header()->setSectionResizeMode(QHeaderView::Stretch);//设置列宽自动分均
m_treeWidget->setColumnCount(2);
QStringList headList;
headList << "node" <<"value";
m_treeWidget->setHeaderLabels(headList);//设置表头
QHBoxLayout* hbox = new QHBoxLayout;
QVBoxLayout* vbox = new QVBoxLayout;
QPushButton* btnOpen = new QPushButton("Open");
QPushButton* btnSave = new QPushButton("Save");
QPushButton* btnSaveAs = new QPushButton("Save As");
connect(btnOpen,&QPushButton::clicked, this, &MainWindow::OnOpen);
connect(btnSave,&QPushButton::clicked, this, &MainWindow::OnSave);
connect(btnSaveAs,&QPushButton::clicked, this, &MainWindow::OnSaveAs);
hbox->addWidget(btnOpen);
hbox->addWidget(btnSave);
hbox->addWidget(btnSaveAs);
hbox->addStretch();
vbox->addLayout(hbox);
vbox->addWidget(m_treeWidget);
widget->setLayout(vbox);
setCentralWidget(widget);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::Read(QDomElement node, QTreeWidgetItem* item)
{
item->setFlags(item->flags() | Qt::ItemIsEditable);
item->setText(0,node.tagName());
if(node.childNodes().length() <=1 )
item->setText(1, node.text());
QDomNamedNodeMap map = node.attributes();
for (int j=0; j< map.length(); j++) {
QTreeWidgetItem* itemTmp = new QTreeWidgetItem;
item->addChild(itemTmp);
itemTmp->setFlags(itemTmp->flags() | Qt::ItemIsEditable);
itemTmp->setText(0,map.item(j).nodeName());
itemTmp->setText(1,map.item(j).nodeValue());
}
QDomNodeList ItemArray = node.childNodes();
for (int i = 0; i<ItemArray.length(); i++) {
QDomElement element = ItemArray.item(i).toElement();
if(element.tagName() != ""){
QTreeWidgetItem* itemTmp = new QTreeWidgetItem;
item->addChild(itemTmp);
Read(element,itemTmp);
}
}
}
void MainWindow::GetData(QDomDocument doc, QDomElement node, QTreeWidgetItem *item)
{
for (int i=0; i<item->childCount(); i++) {
if(item->child(i)->childCount() == 0){
node.setAttribute(item->child(i)->text(0),item->child(i)->text(1));
}else{
QDomElement nodeTmp = doc.createElement(item->child(i)->text(0));
node.appendChild(nodeTmp);
GetData(doc, nodeTmp, item->child(i));
}
}
}
void MainWindow::Save(QString fileName)
{
QFile file(fileName);
if(!file.open(QIODevice::WriteOnly)){
QMessageBox::warning(nullptr,"提示","文件打开失败!");
return;
}
QDomDocument doc;
for (int i=0; i<m_treeWidget->topLevelItemCount(); i++) {
QDomElement node = doc.createElement(m_treeWidget->topLevelItem(i)->text(0));
doc.appendChild(node);
GetData(doc, node, m_treeWidget->topLevelItem(i));
}
QTextStream stream(&file);
doc.save(stream, 4);
file.close();
QMessageBox::information(nullptr,"提示","保存成功!");
}
void MainWindow::OnOpen()
{
m_treeWidget->clear();
QString fileName = QFileDialog::getOpenFileName(nullptr,"选择文件","/","*.xml");
if(fileName.isEmpty()){
QMessageBox::warning(nullptr,"提示","选择文件为空!");
return;
}
QFile file(fileName);
if(!file.open(QIODevice::ReadOnly)){
QMessageBox::warning(nullptr,"提示","文件打开失败!");
return;
}
QDomDocument doc;
QString error;
int row = 0,column = 0 ;
if(!doc.setContent(&file,false,&error,&row,&column)){
QMessageBox::warning(nullptr,"提示","读取xml格式失败!");
return;
}
QTreeWidgetItem* item = new QTreeWidgetItem;
m_treeWidget->addTopLevelItem(item);
QDomElement hRoot = doc.documentElement();
Read(hRoot, item);
file.close();
m_currentFileName = fileName;
}
void MainWindow::OnSave()
{
if(m_currentFileName.isNull()){
QMessageBox::warning(nullptr,"提示","未打开文件!");
return;
}
Save(m_currentFileName);
}
void MainWindow::OnSaveAs()
{
if(m_treeWidget->currentItem() == 0){
QMessageBox::warning(nullptr,"提示","未打开文件!");
return;
}
QString fileName = QFileDialog::getSaveFileName(nullptr,"选择文件","/","*.xml");
if(fileName.isEmpty()){
QMessageBox::warning(nullptr,"提示","选择文件为空!");
return;
}
Save(fileName);
}
到了这里,关于QDomDocument Xml配置文件读写的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!