目錄
一、前言
本例主要講解XML結點的小知識,以及提供QT修改XML文件內容的小例子
二、XML結點知識
例如有個test.xml文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<rootName>
<node1Name1>
<node2Name1>123</node2Name1>
<node2Name2>987</node2Name2>
</node1Name1>
</rootName>
那麼,這個XML文件其實可以分爲3層(根結點層算0層),理論上是這麼一個數據結構
三、結果展示
四、代碼分析
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QDomElement> //新增
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
bool openXmlFile(QString FilePath);
bool changeXml();
private:
Ui::MainWindow *ui;
QDomDocument m_doc; //新增
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
changeXml();
}
MainWindow::~MainWindow()
{
delete ui;
}
bool MainWindow::openXmlFile(QString FilePath)
{
QFile file( FilePath );
if( !file.open( QFile::ReadOnly | QFile::Text ) )
{
qDebug() << QObject::tr("error::ParserXML->OpenXmlFile->file.open->%s\n") << FilePath;
return false;
}
if( !m_doc.setContent( &file ) )
{
qDebug() << QObject::tr("error::ParserXML->OpenXmlFile->doc.setContent\n") << FilePath;
file.close();
return false;
}
file.close();
return true;
}
bool MainWindow::changeXml()
{
QString rootName = "rootName"; //根結點
QString node1Name1 = "node1Name1"; //第1層第1個子結點
QString node2Name1 = "node2Name1"; //第2層第1個子結點
QString node2Name2 = "node2Name2"; //第2層第2個子結點
//獲取文件內容
if(!openXmlFile("./test.xml"))
{
return false;
}
//獲取根結點元素
QDomElement root = m_doc.documentElement();
if(root.tagName().compare(rootName) != 0)
{
qDebug() << "rootName does not match";
return false;
}
//獲取子節點
QDomNode node = root.firstChild();
while ( !node.isNull() )
{
//獲取第1層子結點元素
QDomElement nodeElement = node.toElement();
if(!nodeElement.isNull())
{
//判斷第1層子節點的名字
if( nodeElement.nodeName().compare(node1Name1) == 0)
{
//獲取第1層子節點列表, 並遍歷
QDomNodeList list = nodeElement.childNodes();
for(int i=0; i<list.count(); i++)
{
//獲取第2層第1個/2個子節點
QDomNode node = list.at(i);
if(node.isElement())
{
if( node.nodeName().compare(node2Name1) == 0)
{
//獲取第3層第1個字結點,並修改值
QDomNode oldnode = node.firstChild();
node.firstChild().setNodeValue("csdn");
QDomNode newnode = node.firstChild();
node.replaceChild(newnode,oldnode);
}
if( node.nodeName().compare(node2Name2) == 0)
{
QDomNode oldnode = node.firstChild();
node.firstChild().setNodeValue("www.stu.edu.cn");
QDomNode newnode = node.firstChild();
node.replaceChild(newnode,oldnode);
}
}
}
}
}
//第1層子結點的下一結點
node = node.nextSibling();
}
//重寫入文件
QFile filexml("./test.xml");
if( !filexml.open( QFile::WriteOnly | QFile::Truncate) )
{
qWarning("error::ParserXML->writeOperateXml->file.open\n");
return false;
}
QTextStream ts(&filexml);
ts.reset();
ts.setCodec("utf-8");
m_doc.save(ts, 4, QDomNode::EncodingFromTextStream);
filexml.close();
return true;
}