毕业以来做得时间最长的就是QT客户端程序开发了。在工作里经常遇到Xml文件的读写任务,为了以后省点事,所以抽出点时间写了个DOM方式读写Xml文件的类,因为时间的关系,有些方法没有做足够的测试,使用时间还需要认真测试测试。
头文件:
#ifndef XMLHELPER_H
#define XMLHELPER_H
#include <QDomDocument>
#include <QStringList>
class XmlHelper
{
public:
static XmlHelper* GetInstance();
bool LoadXmlFile(const QString& file_name);
bool CreateXmlDocument(const QString& file_name, const QString& root_node);
bool CreateXmlDocument(const QString& file_name,
const QString& ip, const QString& port);
bool AddXmlNode(QDomElement& parent, const QString& node_tag, const QString& text);
bool AddXmlNode(const QString& parent_tag, const QString& node_tag, const QString& text = "");
bool RemoveXmlNode(const QString& node_tag);
bool ParseXmlDocument(const QString& file_name);
QString ParseXmlNodeContent(const QString& node_tag);
QStringList ParseXmlNodeList(const QString& node_tag);
QString ParseXmlNodeContent(const QDomElement& elem);
QString ParseXmlNodeContent(const QDomNode& special_node);
QString ParseXmlNodeAttribute(const QString& node_tag, const QString& attr_key);
QString ParseXmlNodeAttribute(const QDomElement& elem, const QString& attr_key);
bool SetXmlNodeContent(const QDomElement& elem, const QString& text);
bool SetXmlNodeContent(const QString& tag_name, const QString& text);
bool SetXmlNodeAttribute(const QString& node_tag,
const QString& attr_key, const QString& attr_value);
QDomElement GetXmlRootNode();
QDomElement GetXmlNodeParent(const QString& node_tag);
bool ClearXmlDocument();
bool AddRootNode(const QString &root_node);
private:
XmlHelper() {}
bool LoadXmlFile();
private:
QDomDocument doc_;
QString file_name_;
static XmlHelper *helper_;
};
#endif // XMLHELPER_H
实现文件:
#include "xmlhelper.h"
#include <QFile>
#include <QTextStream>
XmlHelper* XmlHelper::helper_ = NULL;
XmlHelper *XmlHelper::GetInstance()
{
if (helper_ == NULL)
{
helper_ = new XmlHelper;
}
return helper_;
}
bool XmlHelper::LoadXmlFile(const QString &file_name)
{
if (!QFile::exists(file_name))
{
return false;
}
QFile file(file_name);
file_name_ = file_name;
doc_.clear();
if (!file.open(QIODevice::ReadWrite))
{
file.close();
return false;
}
if (!doc_.setContent(&file))
{
file.close();
return false;
}
file.close()