QDomDocument Xml配置文件读写

前言

用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文件

#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文件

#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);

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值