Qt操作xml文件(增删改功能)
这个例子是在根据网上博客《Qt数据库(XML)》改写的一个操作XML的实现。
借鉴了很多里面的代码,大家可以结合上面的博客对照,相信你肯定会对XML的操作熟练起来。
我建立的是Qwidget项目,没有添加ui文件,输出内容都放在应用程序输出中(qDebug)。
XMLtest.pro文件代码:
- #-------------------------------------------------
- #
- # Project created by QtCreator 2012-08-15T15:56:54
- #
- #-------------------------------------------------
- QT += core gui xml
- TARGET = XMLtest
- TEMPLATE = app
- SOURCES += main.cpp\
- widget.cpp
- HEADERS += widget.h
widget.h文件代码:
- #ifndef WIDGET_H
- #define WIDGET_H
- #include <QtGui/QWidget>
- #include <QtCore>
- class Widget : public QWidget
- {
- Q_OBJECT
- public:
- Widget(QWidget *parent = 0);
- ~Widget();
- void read_xml(QString filename);
- void create_xml(QString filename);
- void add_xmlnode(QString filename,QString rmt_name,QString ipa,QString ipb);
- void do_xml(const QString opt,QString filename);
- private:
- };
- #endif // WIDGET_H
widget.cpp文件代码:
- #include "widget.h"
- #include "qfile.h"
- #include "qdebug.h"
- #include <QDomDocument>
- #include "qtextcodec.h"
- Widget::Widget(QWidget *parent)
- : QWidget(parent)
- {
- QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GB2312"));
- QFile *file;
- QString filename = "config.xml";
- if(file->exists("config.xml"))
- {
- read_xml(filename);
- }
- else
- {
- create_xml(filename);
- }
- add_xmlnode(filename,"remote1","127.0.0.1","192.168.1.199");
- do_xml("update",filename);
- }
- Widget::~Widget()
- {
- }
- void Widget::do_xml(const QString opt,QString filename)
- {
- QFile file(filename);
- if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
- {
- qDebug() << "open for do erro";
- file.close();
- }
- QDomDocument doc;
- if(!doc.setContent(&file))
- {
- qDebug() << "setcontent for do error";
- file.close();
- }
- file.close();
- QDomNodeList lists = doc.elementsByTagName("remote");
- QDomElement ele = lists.at(1).toElement();
- if(ele.attribute(tr("id")) == "3")
- {
- if("delete" == opt || "update" == opt)
- {
- QDomElement root = doc.documentElement();
- if("delete" == opt)
- {
- root.removeChild(lists.at(1));
- qDebug() << "remove ok !";
- }
- else
- {
- QDomNodeList child=lists.at(1).childNodes();
- child.at(0).toElement().firstChild().setNodeValue("namechanged");
- child.at(1).toElement().firstChild().setNodeValue("ipachanged");
- child.at(2).toElement().firstChild().setNodeValue("ipbchanged");
- qDebug() << "modify ok !";
- }
- if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
- {
- qDebug() << "open for remove error!";
- }
- QTextStream out(&file);
- doc.save(out,4);
- file.close();
- }
- }
- }
- void Widget::add_xmlnode(QString filename,QString rmt_name, QString ipa, QString ipb)
- {
- QFile file(filename);
- if (!file.open(QIODevice::ReadOnly | QFile::Text)) {
- qDebug()<<"open for add error..." ;
- }
- QDomDocument doc;
- QString errorStr;
- int errorLine;
- int errorColumn;
- if (!doc.setContent(&file, false, &errorStr, &errorLine, &errorColumn)) {
- qDebug()<<"add setcontent error..." ;
- file.close();
- }
- //QDomNode node = doc.firstChild();
- file.close();
- QDomElement root = doc.documentElement();
- if(root.isNull())
- {
- root = doc.createElement("ipconfig");
- }
- QDomElement element_root = doc.createElement(tr("remote"));
- QDomAttr attr_id = doc.createAttribute(tr("id"));
- QDomElement element_rmt = doc.createElement(tr("rmt_name"));
- QDomElement element_ipa = doc.createElement(tr("ipa"));
- QDomElement element_ipb = doc.createElement(tr("ipb"));
- QString str_id;
- if(root.lastChild().isNull())
- {
- str_id = "1";
- attr_id.setValue(str_id);
- }
- else
- {
- str_id = root.lastChild().toElement().attribute(tr("id"));
- int count = str_id.toInt()+1;
- attr_id.setValue(QString::number(count));
- }
- QDomText text;
- text =doc.createTextNode(rmt_name);
- element_rmt.appendChild(text);
- text = doc.createTextNode(ipa);
- element_ipa.appendChild(text);
- text = doc.createTextNode(ipb);
- element_ipb.appendChild(text);
- text.clear();
- element_root.appendChild(element_rmt);
- element_root.appendChild(element_ipa);
- element_root.appendChild(element_ipb);
- element_root.setAttributeNode(attr_id);
- root.appendChild(element_root);
- if(!file.open(QIODevice::WriteOnly|QIODevice::Append))
- qDebug() << "open for add error!";
- QTextStream out(&file);
- doc.save(out,4);
- file.close();
- }
- void Widget::read_xml(QString filename)
- {
- QFile file(filename);
- if (!file.open(QIODevice::ReadOnly | QFile::Text)) {
- qDebug()<<"open for read error..." ;
- }
- QString errorStr;
- int errorLine;
- int errorColumn;
- QDomDocument doc;
- if (!doc.setContent(&file, false, &errorStr, &errorLine, &errorColumn)) {
- qDebug()<<"setcontent error..." ;
- file.close();
- }
- file.close();
- QDomElement root = doc.documentElement();
- if (root.tagName() != "ipconfig") {
- qDebug()<<"root.tagname != ipconfig..." ;
- }
- QDomNode node = root.firstChild();
- while(!node.isNull())
- {
- if(node.isElement())
- {
- QDomElement element = node.toElement();
- qDebug() << qPrintable(element.tagName())<<qPrintable(element.attribute("id"));
- QDomNodeList list = element.childNodes();
- for(int i = 0;i < list.count();i++)
- {
- QDomNode nodechild = list.at(i);
- if(nodechild.isElement())
- {
- qDebug() << " " << qPrintable(nodechild.toElement().tagName()) << qPrintable(nodechild.toElement().text());
- }
- }
- }
- node = node.nextSibling();
- }
- }
- void Widget::create_xml(QString filename)
- {
- QFile file(filename);
- file.open(QIODevice::ReadWrite);
- QDomDocument doc;
- QDomProcessingInstruction instruction;
- instruction = doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"GB2312\"");
- doc.appendChild(instruction);
- QDomElement root = doc.createElement("ipconfig");
- doc.appendChild(root);
- QDomText text = doc.createTextNode("");
- root.appendChild(text);
- QTextStream out(&file);
- doc.save(out,4);
- file.close();
- }
main.cpp文件代码:
- #include <QtGui/QApplication>
- #include "widget.h"
- int main(int argc, char *argv[])
- {
- QApplication a(argc, argv);
- Widget w;
- w.show();
- return a.exec();
- }
XML文件结构:
- <?xml version='1.0' encoding='GB2312'?>
- <ipconfig>
- <remote id="1">
- <rmt_name>remote1</rmt_name>
- <ipa>127.0.0.1</ipa>
- <ipb>192.168.1.199</ipb>
- </remote>
- <remote id="3">
- <rmt_name>namechanged</rmt_name>
- <ipa>ipachanged</ipa>
- <ipb>ipbchanged</ipb>
- </remote>
- <remote id="4">
- <rmt_name>remote1</rmt_name>
- <ipa>127.0.0.1</ipa>
- <ipb>192.168.1.199</ipb>
- </remote>
- <remote id="5">
- <rmt_name>remote1</rmt_name>
- <ipa>127.0.0.1</ipa>
- <ipb>192.168.1.199</ipb>
- </remote>
- <remote id="6">
- <rmt_name>remote1</rmt_name>
- <ipa>127.0.0.1</ipa>
- <ipb>192.168.1.199</ipb>
- </remote>
- <remote id="7">
- <rmt_name>remote1</rmt_name>
- <ipa>127.0.0.1</ipa>
- <ipb>192.168.1.199</ipb>
- </remote>
- <remote id="8">
- <rmt_name>remote1</rmt_name>
- <ipa>127.0.0.1</ipa>
- <ipb>192.168.1.199</ipb>
- </remote>
- </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文件(增删改功能)的更多相关文章
- java实现xml文件增删改查
java一次删除xml多个节点: 方案1.你直接改动了nodeList,这一般在做循环时是不同意直接这么做的. 你能够尝试在遍历一个list时,在循环体同一时候删除list里的内容,你会得到一个异常. ...
- flex 操作xml 实现增删改查 .
一 在介绍Flex中操作XML之前,首先简单介绍下XML中的基本术语. 元素:XML中拥有开始标签和结束标签的这一块称为“元素” 节点:把XML元素与文本结合起来统称为节点 根节点:位于整 ...
- .NET XML文件增删改查
查询 采用的是DataSet 的 ReadXML方法. DataSet ds = new System.Data.DataSet(); ds.ReadXml("bdc.xml"); ...
- Asp.Net 操作XML文件的增删改查 利用GridView
不废话,直接上如何利用Asp.NET操作XML文件,并对其属性进行修改,刚开始的时候,是打算使用JS来控制生成XML文件的,但是最后却是无法创建文件,读取文件则没有使用了 index.aspx 文件 ...
- Qt之QDomDocument操作xml文件-模拟ini文件存储
一.背景 不得不说Qt是一个很强大的类库,不管是做项目还是做产品,Qt自身封装的东西就已经非常全面了,我们今天的这篇文章就是模拟了Qt读写ini文件的一个操作,当然是由于一些外力原因,我们决定自己来完 ...
- java中XML操作:xml与string互转、读取XML文档节点及对XML节点增删改查
一.XML和String互转: 使用dom4j程式变得很简单 //字符串转XML String xmlStr = \"......\"; Document document = D ...
- JAVA中通过Jaxp操作XML文件基础
Java中有多种方式操作XML文件,目前讲一讲以SUN公司提供的DocumentBuilderFactory工厂类对象操作XML. 使用XML基本操作就是需要CRUD(增删改查),那么首先通过一个查询 ...
- 使用idea对XML的增删改查
XML:是一种可扩展标记性的语言,与java语言无关,它可以自定义标签. 1.首先需要到导入Dom4j架包,与自己所时候的ide关联 2.编写自己的xml文件,入上图所示(里面的所有元素及元素中的属性 ...
- C#基础知识---Linq操作XML文件
概述 Linq也就是Language Integrated Query的缩写,即语言集成查询,是微软在.Net 3.5中提出的一项新技术. Linq主要包含4个组件---Linq to Objects ...
随机推荐
- Hibernate配置文件学习心得
Hibernate配置文件在工程中十分重要,名称为Hibernate.cfg.xml;如下图: 在代码模式下图: 第一句由于没怎么改动过,所以至今不知道有什么作用: <property name ...
- php广告显示设置存放记录的目录代码
<?php #########随机广告显示########## function myads(){ $dir="ads"; #设置存放记录的目录 //$dir="a ...
- lucene 3.0.2 中文分词
package lia.meetlucene; import java.io.IOException; import java.io.Reader; import java.io.StringRead ...
- 分布式架构高可用架构篇_01_zookeeper集群的安装、配置、高可用测试
参考: 龙果学院http://www.roncoo.com/share.html?hamc=hLPG8QsaaWVOl2Z76wpJHp3JBbZZF%2Bywm5vEfPp9LbLkAjAnB%2B ...
- QQ、淘宝、阿里旺旺在线网页链接代码及详解 很实用
你可直接到官网去生成代码,简单.方便,相信都能上网的你,对这不会有难度的,认识字的就行,赶紧去吧! 1.阿里旺旺官网: http://page.1688.com/html/wangwang/dow ...
- 每天php函数 - floatval() 获取变量的浮点值
float floatval ( mixed $var ) 返回变量 var的 float 数值. var 可以是任何标量类型.你不能将 floatval() 用于数组或对象. <?php$va ...
- Memcache 提高缓存命中率
最近手上某个项目跟新代码,新的代码里大量采用memcahce作为缓存.所以开始深入了解memcache的内存分配策略.以前就听说有个PHP写的memcache监控脚本,在网上搜索了一下,果断下载下来用 ...
- php thread
1-include('w_fun.php');页面已经在执行,则修改include中的函数,倒置旧页面不受影响:新页面生效:2-time 轮流 echo ' <script> windo ...
- diy-pagination-javascript 分页
<?php isset($_REQUEST['form_single_page_num']) && !empty($_REQUEST['form_single_page_num' ...
- PowerDesigner连接MySQL,建立逆向工程图解
传说中,程序员们喜欢用powerDesign进行数据库建模.通常都是先设计出物理模型图,在转换出数据库需要的SQL语句,从而生成数据库.但,江湖中流传着"powerDesign逆向工程&qu ...