Qt下读写XML格式文件(使用QDomDocument类)

简述

XML是一种标记语言,被设计用来结构化存储以及传输信息,是一种常用的文档数据结构。
就我个人而言,Qt下读写XML格式文件可以有三种方法:
一是使用纯C++的rapidxml开源库。优点是速度快,媲美strlen()的速度;缺点是处理中文比较麻烦,编码只有ANSI格式。
二是使用QXmlStreamReader类,适当结合QXmlQuery类。优点是灵活性强,节约内存;缺点是理解起来相对较难,还需要一点数据库语言的知识。
三是使用QDomDocument类。是Qt下读写xml文件传统而普遍的做法,缺点就是如果读写的文件很大,会消耗大量的内存空间。
QDomDocument类可以理解为一个QFile,这个类的对象代表了整个文件,通常也是一个xml文件的主节点。还需使用到的类有QDomNode(节点基类)、QDomElement(节点类)、QDomText(内容)、QDomAttr(属性)、QDomProcessingInstruction(文件头)。

代码之路

读写一个用户名文件"user.xml",文件内容如下:

<?xml version = "1.0" encoding = "UTF-8"?>
<ALL>
  <DATA>
      <Name>1</Name>
      <Password>12</Password>
      <Describe>123</Describe>
      <Flag>1</Flag>
  </DATA>
  <DATA>
      <Name>2</Name>
      <Password>22</Password>
      <Describe>234</Describe>
      <Flag>1</Flag>
  </DATA>
</ALL>

读取上述内容的xml文件到一个结构体中

//用户信息结构体
struct UserStruct
{
  QString username; 
  QString password;
  QString decribe;
  int flag;    //用户权限
  void clear()
  {
    username = "";
    password = "";
    describe = "";
    flag = 1;
  }
};

读xml格式函数代码如下:

void readUserxml()
{
  UserStruct tmpInfo;
  QFile file(filename);
  if (!file.open(QIODevice::ReadOnly|QIODevice::Text))
  {
  	return;
  }
  QDomDocument doc;  //xml格式文件
  if (!doc.setContent(&file))
  {
  	file.close();
  	return;
  }
  file.close();
  QDomElement root = doc.documentElement(); //节点 ALL
    if (!root.isNull())
    {
        QDomNode node_a = root.firstChild(); //节点DATA
        while (!node_a.isNull())
        {
            QDomElement node_all = node_a.toElement(); //QDomnode转成QDomElement
            if (!node_all.isNull())
            {
                tmpInfo.clear(); //清空
                QDomElement n_name = node_all.firstChildElement("Name"); //Name节点

                if (!n_name.isNull())
                {
                    tmpInfo.username = n_name.text();
                }
                QDomElement n_passwd = node_all.firstChildElement("Password"); //Password节点
                if (!n_passwd.isNull())
                {
                    tmpInfo.password = n_passwd.text();
                }
                QDomElement n_describe = node_all.firstChildElement("Describe"); //Describe节点
                if (!n_describe.isNull())
                {
                    tmpInfo.describe = n_describe.text();
                }
                QDomElement n_flag = node_all.firstChildElement("Flag"); //Flag节点
                if (!n_flag.isNull())
                {
                    tmpInfo.flag  = n_flag.text().toInt();
                }

             //   //加入vector
             //   UserInfo.push_back(tmpInfo);
            }
            node_a = node_a.nextSibling();       //读取下一个DATA节点
        }
    }
}

写XML格式文件

void writeUserxml()
{
    //写入xml
    QFile file(Filename);
    if (!file.open(QIODevice::WriteOnly|QIODevice::Text|QIODevice::Truncate))
    {
        return;
    }
    QDomDocument doc;
    QDomProcessingInstruction instruction;
    instruction = doc.createProcessingInstruction("xml", "version = \"1.0\" encoding = \"UTF-8\"");
    doc.appendChild(instruction);         //写入文件头

    QDomElement root = doc.createElement("ALL");
    doc.appendChild(root);

//    UserStruct tmp;
//    tmp.username = "11";
//    tmp.password = "1234";
//    tmp.describe = "321";
//    tmp.flag = 1;
//    UserInfo.push_back(tmp);

    int sum = UserInfo.size();

//    struct UserStruct
//    {
//        QString username;
//        QString password;
//        QString describe;
//        int flag;
//    };

    for (int i = 0; i < sum; ++i)
    {
        QDomElement node_data = doc.createElement("DATA");
        QDomElement node_name = doc.createElement("Name");
        QDomElement node_passwd = doc.createElement("Password");
        QDomElement node_describe = doc.createElement("Describe");
        QDomElement node_flag = doc.createElement("Flag");

        node_name.appendChild(doc.createTextNode(UserInfo[i].username));
        node_passwd.appendChild(doc.createTextNode(UserInfo[i].password));
        node_describe.appendChild(doc.createTextNode(UserInfo[i].describe));
        node_flag.appendChild(doc.createTextNode(QString::number(UserInfo[i].flag)));

        node_data.appendChild(node_name);
        node_data.appendChild(node_passwd);
        node_data.appendChild(node_describe);
        node_data.appendChild(node_flag);

        root.appendChild(node_data);
    }
    QTextStream out(&file);
    doc.save(out, 4);     //写入文件中
    file.close();
}

例子中没有涉及到节点属性,下面补充一下节点属性的写入:

QDomAttr atr = doc.createAttribute("id");
atr.setValue(str_id);
node_date.setAttributeNode(atr);

总结

Qt下使用QDomdocument类书写xml代码量相对不少,但是思路还是很清晰的。

  • 7
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,这是一个关于 Qt 的问题。QDomDocumentQt 中用于读写 XML 文件的。其主要功能是将 XML 文件解析成 DOM 树表示,从而可以方便地进行修改、查询和输出操作。 在 Qt使用 QDomDocument 读写 XML 文件的步骤如下: 1. 创建 QDomDocument 对象,并设置 XML 文件的版本、编码和根节点。 2. 通过 QDomDocument 对象的 createElement() 方法创建节点,并通过 appendChild() 方法将其添加到 DOM 树中。 3. 通过 QDomDocument 对象的 createTextNode() 方法创建文本节点,并通过 appendChild() 方法将其添加到 DOM 树中。 4. 通过 QDomDocument 对象的 toByteArray() 方法将 DOM 树输出到字节数组中,或通过 save() 方法将 DOM 树保存到 XML 文件中。 以下是一个简单的示例代码,演示了如何使用 QDomDocument 读写 XML 文件: ```cpp #include <QFile> #include <QDomDocument> int main() { // 创建 QDomDocument 对象 QDomDocument doc; // 设置 XML 文件的版本和编码 doc.appendChild(doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"")); // 创建根节点 QDomElement root = doc.createElement("root"); doc.appendChild(root); // 创建子节点 QDomElement child = doc.createElement("child"); root.appendChild(child); // 创建文本节点 QDomText text = doc.createTextNode("Hello, world!"); child.appendChild(text); // 将 DOM 树输出到字节数组中 QByteArray xml = doc.toByteArray(); // 将 DOM 树保存到 XML 文件中 QFile file("test.xml"); if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream out(&file); out << doc.toString(); file.close(); } return 0; } ``` 这段代码创建了一个名为 test.xmlXML 文件,其内容为: ```xml <?xml version="1.0" encoding="UTF-8"?> <root> <child>Hello, world!</child> </root> ``` 希望这个示例代码可以帮助你了解如何使用 QDomDocumentQt读写 XML 文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值