这个例子是在根据网上博客《Qt数据库(XML)》改写的一个操作XML的实现。

借鉴了很多里面的代码,大家可以结合上面的博客对照,相信你肯定会对XML的操作熟练起来。

我建立的是Qwidget项目,没有添加ui文件,输出内容都放在应用程序输出中(qDebug)。

XMLtest.pro文件代码:

  1. #-------------------------------------------------
  2. #
  3. # Project created by QtCreator 2012-08-15T15:56:54
  4. #
  5. #-------------------------------------------------
  6. QT       += core gui xml
  7. TARGET = XMLtest
  8. TEMPLATE = app
  9. SOURCES += main.cpp\
  10. widget.cpp
  11. HEADERS  += widget.h

widget.h文件代码:

  1. #ifndef WIDGET_H
  2. #define WIDGET_H
  3. #include <QtGui/QWidget>
  4. #include <QtCore>
  5. class Widget : public QWidget
  6. {
  7. Q_OBJECT
  8. public:
  9. Widget(QWidget *parent = 0);
  10. ~Widget();
  11. void read_xml(QString filename);
  12. void create_xml(QString filename);
  13. void add_xmlnode(QString filename,QString rmt_name,QString ipa,QString ipb);
  14. void do_xml(const QString opt,QString filename);
  15. private:
  16. };
  17. #endif // WIDGET_H

widget.cpp文件代码:

  1. #include "widget.h"
  2. #include "qfile.h"
  3. #include "qdebug.h"
  4. #include <QDomDocument>
  5. #include "qtextcodec.h"
  6. Widget::Widget(QWidget *parent)
  7. : QWidget(parent)
  8. {
  9. QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GB2312"));
  10. QFile *file;
  11. QString  filename = "config.xml";
  12. if(file->exists("config.xml"))
  13. {
  14. read_xml(filename);
  15. }
  16. else
  17. {
  18. create_xml(filename);
  19. }
  20. add_xmlnode(filename,"remote1","127.0.0.1","192.168.1.199");
  21. do_xml("update",filename);
  22. }
  23. Widget::~Widget()
  24. {
  25. }
  26. void Widget::do_xml(const QString opt,QString filename)
  27. {
  28. QFile file(filename);
  29. if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
  30. {
  31. qDebug() << "open for do erro";
  32. file.close();
  33. }
  34. QDomDocument doc;
  35. if(!doc.setContent(&file))
  36. {
  37. qDebug() << "setcontent for do error";
  38. file.close();
  39. }
  40. file.close();
  41. QDomNodeList lists = doc.elementsByTagName("remote");
  42. QDomElement ele = lists.at(1).toElement();
  43. if(ele.attribute(tr("id")) == "3")
  44. {
  45. if("delete" == opt || "update" == opt)
  46. {
  47. QDomElement root = doc.documentElement();
  48. if("delete" == opt)
  49. {
  50. root.removeChild(lists.at(1));
  51. qDebug() << "remove ok !";
  52. }
  53. else
  54. {
  55. QDomNodeList child=lists.at(1).childNodes();
  56. child.at(0).toElement().firstChild().setNodeValue("namechanged");
  57. child.at(1).toElement().firstChild().setNodeValue("ipachanged");
  58. child.at(2).toElement().firstChild().setNodeValue("ipbchanged");
  59. qDebug() << "modify ok !";
  60. }
  61. if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
  62. {
  63. qDebug() << "open for remove error!";
  64. }
  65. QTextStream out(&file);
  66. doc.save(out,4);
  67. file.close();
  68. }
  69. }
  70. }
  71. void Widget::add_xmlnode(QString filename,QString rmt_name, QString ipa, QString ipb)
  72. {
  73. QFile file(filename);
  74. if (!file.open(QIODevice::ReadOnly | QFile::Text)) {
  75. qDebug()<<"open for add error..." ;
  76. }
  77. QDomDocument doc;
  78. QString errorStr;
  79. int errorLine;
  80. int errorColumn;
  81. if (!doc.setContent(&file, false, &errorStr, &errorLine, &errorColumn)) {
  82. qDebug()<<"add setcontent error..." ;
  83. file.close();
  84. }
  85. //QDomNode node = doc.firstChild();
  86. file.close();
  87. QDomElement root = doc.documentElement();
  88. if(root.isNull())
  89. {
  90. root = doc.createElement("ipconfig");
  91. }
  92. QDomElement element_root = doc.createElement(tr("remote"));
  93. QDomAttr attr_id = doc.createAttribute(tr("id"));
  94. QDomElement element_rmt = doc.createElement(tr("rmt_name"));
  95. QDomElement element_ipa = doc.createElement(tr("ipa"));
  96. QDomElement element_ipb = doc.createElement(tr("ipb"));
  97. QString str_id;
  98. if(root.lastChild().isNull())
  99. {
  100. str_id = "1";
  101. attr_id.setValue(str_id);
  102. }
  103. else
  104. {
  105. str_id = root.lastChild().toElement().attribute(tr("id"));
  106. int count = str_id.toInt()+1;
  107. attr_id.setValue(QString::number(count));
  108. }
  109. QDomText text;
  110. text =doc.createTextNode(rmt_name);
  111. element_rmt.appendChild(text);
  112. text = doc.createTextNode(ipa);
  113. element_ipa.appendChild(text);
  114. text = doc.createTextNode(ipb);
  115. element_ipb.appendChild(text);
  116. text.clear();
  117. element_root.appendChild(element_rmt);
  118. element_root.appendChild(element_ipa);
  119. element_root.appendChild(element_ipb);
  120. element_root.setAttributeNode(attr_id);
  121. root.appendChild(element_root);
  122. if(!file.open(QIODevice::WriteOnly|QIODevice::Append))
  123. qDebug() << "open for add error!";
  124. QTextStream out(&file);
  125. doc.save(out,4);
  126. file.close();
  127. }
  128. void Widget::read_xml(QString filename)
  129. {
  130. QFile file(filename);
  131. if (!file.open(QIODevice::ReadOnly | QFile::Text)) {
  132. qDebug()<<"open for read error..." ;
  133. }
  134. QString errorStr;
  135. int errorLine;
  136. int errorColumn;
  137. QDomDocument doc;
  138. if (!doc.setContent(&file, false, &errorStr, &errorLine, &errorColumn)) {
  139. qDebug()<<"setcontent error..." ;
  140. file.close();
  141. }
  142. file.close();
  143. QDomElement root = doc.documentElement();
  144. if (root.tagName() != "ipconfig") {
  145. qDebug()<<"root.tagname != ipconfig..." ;
  146. }
  147. QDomNode node = root.firstChild();
  148. while(!node.isNull())
  149. {
  150. if(node.isElement())
  151. {
  152. QDomElement element = node.toElement();
  153. qDebug() << qPrintable(element.tagName())<<qPrintable(element.attribute("id"));
  154. QDomNodeList list = element.childNodes();
  155. for(int i = 0;i < list.count();i++)
  156. {
  157. QDomNode nodechild = list.at(i);
  158. if(nodechild.isElement())
  159. {
  160. qDebug() << "    " << qPrintable(nodechild.toElement().tagName()) << qPrintable(nodechild.toElement().text());
  161. }
  162. }
  163. }
  164. node = node.nextSibling();
  165. }
  166. }
  167. void Widget::create_xml(QString filename)
  168. {
  169. QFile file(filename);
  170. file.open(QIODevice::ReadWrite);
  171. QDomDocument doc;
  172. QDomProcessingInstruction instruction;
  173. instruction = doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"GB2312\"");
  174. doc.appendChild(instruction);
  175. QDomElement root = doc.createElement("ipconfig");
  176. doc.appendChild(root);
  177. QDomText text = doc.createTextNode("");
  178. root.appendChild(text);
  179. QTextStream out(&file);
  180. doc.save(out,4);
  181. file.close();
  182. }

main.cpp文件代码:

  1. #include <QtGui/QApplication>
  2. #include "widget.h"
  3. int main(int argc, char *argv[])
  4. {
  5. QApplication a(argc, argv);
  6. Widget w;
  7. w.show();
  8. return a.exec();
  9. }

XML文件结构:

  1. <?xml version='1.0' encoding='GB2312'?>
  2. <ipconfig>
  3. <remote id="1">
  4. <rmt_name>remote1</rmt_name>
  5. <ipa>127.0.0.1</ipa>
  6. <ipb>192.168.1.199</ipb>
  7. </remote>
  8. <remote id="3">
  9. <rmt_name>namechanged</rmt_name>
  10. <ipa>ipachanged</ipa>
  11. <ipb>ipbchanged</ipb>
  12. </remote>
  13. <remote id="4">
  14. <rmt_name>remote1</rmt_name>
  15. <ipa>127.0.0.1</ipa>
  16. <ipb>192.168.1.199</ipb>
  17. </remote>
  18. <remote id="5">
  19. <rmt_name>remote1</rmt_name>
  20. <ipa>127.0.0.1</ipa>
  21. <ipb>192.168.1.199</ipb>
  22. </remote>
  23. <remote id="6">
  24. <rmt_name>remote1</rmt_name>
  25. <ipa>127.0.0.1</ipa>
  26. <ipb>192.168.1.199</ipb>
  27. </remote>
  28. <remote id="7">
  29. <rmt_name>remote1</rmt_name>
  30. <ipa>127.0.0.1</ipa>
  31. <ipb>192.168.1.199</ipb>
  32. </remote>
  33. <remote id="8">
  34. <rmt_name>remote1</rmt_name>
  35. <ipa>127.0.0.1</ipa>
  36. <ipb>192.168.1.199</ipb>
  37. </remote>
  38. </ipconfig>

应用程序输出:

remote 1

rmt_name remote1

ipa 127.0.0.1

ipb 192.168.1.199

remote 3

rmt_name remote1

ipa 127.0.0.1

ipb 192.168.1.199

remote 4

rmt_name remote1

ipa 127.0.0.1

ipb 192.168.1.199

remote 5

rmt_name remote1

ipa 127.0.0.1

ipb 192.168.1.199

remote 6

rmt_name remote1

ipa 127.0.0.1

ipb 192.168.1.199

remote 7

rmt_name remote1

ipa 127.0.0.1

ipb 192.168.1.199

modify ok !

Qt操作xml文件(增删改功能)的更多相关文章

  1. java实现xml文件增删改查

    java一次删除xml多个节点: 方案1.你直接改动了nodeList,这一般在做循环时是不同意直接这么做的. 你能够尝试在遍历一个list时,在循环体同一时候删除list里的内容,你会得到一个异常. ...

  2. flex 操作xml 实现增删改查 .

    一 在介绍Flex中操作XML之前,首先简单介绍下XML中的基本术语. 元素:XML中拥有开始标签和结束标签的这一块称为“元素”    节点:把XML元素与文本结合起来统称为节点    根节点:位于整 ...

  3. .NET XML文件增删改查

    查询 采用的是DataSet 的 ReadXML方法. DataSet ds = new System.Data.DataSet(); ds.ReadXml("bdc.xml"); ...

  4. Asp.Net 操作XML文件的增删改查 利用GridView

    不废话,直接上如何利用Asp.NET操作XML文件,并对其属性进行修改,刚开始的时候,是打算使用JS来控制生成XML文件的,但是最后却是无法创建文件,读取文件则没有使用了 index.aspx 文件 ...

  5. Qt之QDomDocument操作xml文件-模拟ini文件存储

    一.背景 不得不说Qt是一个很强大的类库,不管是做项目还是做产品,Qt自身封装的东西就已经非常全面了,我们今天的这篇文章就是模拟了Qt读写ini文件的一个操作,当然是由于一些外力原因,我们决定自己来完 ...

  6. java中XML操作:xml与string互转、读取XML文档节点及对XML节点增删改查

    一.XML和String互转: 使用dom4j程式变得很简单 //字符串转XML String xmlStr = \"......\"; Document document = D ...

  7. JAVA中通过Jaxp操作XML文件基础

    Java中有多种方式操作XML文件,目前讲一讲以SUN公司提供的DocumentBuilderFactory工厂类对象操作XML. 使用XML基本操作就是需要CRUD(增删改查),那么首先通过一个查询 ...

  8. 使用idea对XML的增删改查

    XML:是一种可扩展标记性的语言,与java语言无关,它可以自定义标签. 1.首先需要到导入Dom4j架包,与自己所时候的ide关联 2.编写自己的xml文件,入上图所示(里面的所有元素及元素中的属性 ...

  9. C#基础知识---Linq操作XML文件

    概述 Linq也就是Language Integrated Query的缩写,即语言集成查询,是微软在.Net 3.5中提出的一项新技术. Linq主要包含4个组件---Linq to Objects ...

随机推荐

  1. MySQL中的datetime与timestamp比较-------转载

    原文地址http://database.51cto.com/art/200905/124240.htm MySQL中的datetime与timestamp比较 本文将通过实例比较MySQL中的date ...

  2. CSS系列:长度单位&字体大小的关系em rem px

    em是相对长度单位.相对于当前对象内文本的字体尺寸.如当前对行内文本的字体尺寸未被人为设置,则相对于浏览器的默认字体尺寸. 任意浏览器的默认字体高都是16px.所有未经调整的浏览器都符合: 1em=1 ...

  3. Linux权限问题

    Linux中各个用户对文件和目录的权限有三种: r: 读 w:写 x:执行 各个权限的意义: 文件 r:可以读取文件的内容 w:编辑文件内容 x:执行该文件 目录 r:列出该目录下的内容,即使用ls命 ...

  4. sql in查询排序

    1.默认下,使用select xxx where in(xx,xx)查询,返回结果是按主键排序的,如果要按in()中值的排列顺序,可以这样做:   select * from talbe where ...

  5. XBox 开发者大会

    今天参加了微软的Xbox开发者大会,虽然没我什么事情,不过还是有不少的收获,随便说说自己的一点感受吧. 先上几张图,附带妹子一个,不过手机不清楚哈,~~ 1 ID@XBOX开发者计划与独立游戏开发者 ...

  6. osal_start_timerEx(Lock_TaskID,SBP_START_DEVICE_EVT,SBP_PERIODIC_EVT_PERIOD)的理解

    osal_start_timerEx(Lock_TaskID,SBP_START_DEVICE_EVT,SBP_PERIODIC_EVT_PERIOD)与osal_set_event(Music_Ta ...

  7. Ruby--正则

    1. 只取数字(用的是字符串替换) gsub(/[^0-9]/, “”)

  8. mysqli_query($link,'SET group_concat_max_len=8192');

    mysqli_query($link,'SET group_concat_max_len=8192'); $sql = 'SELECT GROUP_CONCAT(w) FROM ---'; mysql ...

  9. C++ char*,const char*,string的相互转换

    1. string转const char* string s ="abc";constchar* c_s = s.c_str(); 2. const char*转string   ...

  10. 线程池ThreadPoolExecutor

    线程池类为 java.util.concurrent.ThreadPoolExecutor,常用构造方法为: ThreadPoolExecutor(int corePoolSize, int maxi ...