示例1
1.xml 是QT 另外需要手动添加的模块。 在pro 文件中需要手动添加: QT += xml
2.xml头文件需要用到#include<QtXml>
, 当然这是包含了xml 所有的内容, 如果相只操作其中部分功能, 可以使用 #include<QtXml/对应的类名> ,也可以也可以include <QDomDocument>
,当然本实例中还用到了#include <QFile>
用于文件的保存,#include <QFileDialog>
让用户自己选择保存路径。
.pro 文件
QT += core xml
QT -= gui
TARGET = xmltest
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
main.cpp
#include <QCoreApplication>
#include <QtXml> //也可以include <QDomDocument>
//写xml
void WriteXml()
{
//打开或创建文件
QFile file("test.xml"); //相对路径、绝对路径、资源路径都可以
if(!file.open(QFile::WriteOnly|QFile::Truncate)) //可以用QIODevice,Truncate表示清空原来的内容
return;
QDomDocument doc;
//写入xml头部
QDomProcessingInstruction instruction; //添加处理命令
instruction=doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"UTF-8\"");
doc.appendChild(instruction);
//添加根节点
QDomElement root=doc.createElement("library");
doc.appendChild(root);
//添加第一个子节点及其子元素
QDomElement book=doc.createElement("book");
book.setAttribute("id",1); //方式一:创建属性 其中键值对的值可以是各种类型
QDomAttr time=doc.createAttribute("time"); //方式二:创建属性 值必须是字符串
time.setValue("2013/6/13");
book.setAttributeNode(time);
QDomElement title=doc.createElement("title"); //创建子元素
QDomText text; //设置括号标签中间的值
text=doc.createTextNode("C++ primer");
book.appendChild(title);
title.appendChild(text);
QDomElement author=doc.createElement("author"); //创建子元素
text=doc.createTextNode("Stanley Lippman");
author.appendChild(text);
book.appendChild(author);
root.appendChild(book);
//添加第二个子节点及其子元素,部分变量只需重新赋值
book=doc.createElement("book");
book.setAttribute("id",2);
time=doc.createAttribute("time");
time.setValue("2007/5/25");
book.setAttributeNode(time);
title=doc.createElement("title");
text=doc.createTextNode("Thinking in Java");
book.appendChild(title);
title.appendChild(text);
author=doc.createElement("author");
text=doc.createTextNode("Bruce Eckel");
author.appendChild(text);
book.appendChild(author);
root.appendChild(book);
//输出到文件
QTextStream out_stream(&file);
doc.save(out_stream,4); //缩进4格
file.close();
}
//读xml
void ReadXml()
{
//打开或创建文件
QFile file("test.xml"); //相对路径、绝对路径、资源路径都行
if(!file.open(QFile::ReadOnly))
return;
QDomDocument doc;
if(!doc.setContent(&file))
{
file.close();
return;
}
file.close();
QDomElement root=doc.documentElement(); //返回根节点
qDebug()<<root.nodeName();
QDomNode node=root.firstChild(); //获得第一个子节点
while(!node.isNull()) //如果节点不空
{
if(node.isElement()) //如果节点是元素
{
QDomElement e=node.toElement(); //转换为元素,注意元素和节点是两个数据结构,其实差不多
qDebug()<<e.tagName()<<" "<<e.attribute("id")<<" "<<e.attribute("time"); //打印键值对,tagName和nodeName是一个东西
QDomNodeList list=e.childNodes();
for(int i=0;i<list.count();i++) //遍历子元素,count和size都可以用,可用于标签数计数
{
QDomNode n=list.at(i);
if(node.isElement())
qDebug()<<n.nodeName()<<":"<<n.toElement().text();
}
}
node=node.nextSibling(); //下一个兄弟节点,nextSiblingElement()是下一个兄弟元素,都差不多
}
}
//增加xml内容
void AddXml()
{
//打开文件
QFile file("test.xml"); //相对路径、绝对路径、资源路径都可以
if(!file.open(QFile::ReadOnly))
return;
//增加一个一级子节点以及元素
QDomDocument doc;
if(!doc.setContent(&file))
{
file.close();
return;
}
file.close();
QDomElement root=doc.documentElement();
QDomElement book=doc.createElement("book");
book.setAttribute("id",3);
book.setAttribute("time","1813/1/27");
QDomElement title=doc.createElement("title");
QDomText text;
text=doc.createTextNode("Pride and Prejudice");
title.appendChild(text);
book.appendChild(title);
QDomElement author=doc.createElement("author");
text=doc.createTextNode("Jane Austen");
author.appendChild(text);
book.appendChild(author);
root.appendChild(book);
if(!file.open(QFile::WriteOnly|QFile::Truncate)) //先读进来,再重写,如果不用truncate就是在后面追加内容,就无效了
return;
//输出到文件
QTextStream out_stream(&file);
doc.save(out_stream,4); //缩进4格
file.close();
}
//删减xml内容
void RemoveXml()
{
//打开文件
QFile file("test.xml"); //相对路径、绝对路径、资源路径都可以
if(!file.open(QFile::ReadOnly))
return;
//删除一个一级子节点及其元素,外层节点删除内层节点于此相同
QDomDocument doc;
if(!doc.setContent(&file))
{
file.close();
return;
}
file.close(); //一定要记得关掉啊,不然无法完成操作
QDomElement root=doc.documentElement();
QDomNodeList list=doc.elementsByTagName("book"); //由标签名定位
for(int i=0;i<list.count();i++)
{
QDomElement e=list.at(i).toElement();
if(e.attribute("time")=="2007/5/25") //以属性名定位,类似于hash的方式,warning:这里仅仅删除一个节点,其实可以加个break
root.removeChild(list.at(i));
}
if(!file.open(QFile::WriteOnly|QFile::Truncate))
return;
//输出到文件
QTextStream out_stream(&file);
doc.save(out_stream,4); //缩进4格
file.close();
}
//更新xml内容
void UpdateXml()
{
//打开文件
QFile file("test.xml"); //相对路径、绝对路径、资源路径都可以
if(!file.open(QFile::ReadOnly))
return;
//更新一个标签项,如果知道xml的结构,直接定位到那个标签上定点更新
//或者用遍历的方法去匹配tagname或者attribut,value来更新
QDomDocument doc;
if(!doc.setContent(&file))
{
file.close();
return;
}
file.close();
QDomElement root=doc.documentElement();
QDomNodeList list=root.elementsByTagName("book");
QDomNode node=list.at(list.size()-1).firstChild(); //定位到第三个一级子节点的子元素
QDomNode oldnode=node.firstChild(); //标签之间的内容作为节点的子节点出现,当前是Pride and Projudice
node.firstChild().setNodeValue("Emma");
QDomNode newnode=node.firstChild();
node.replaceChild(newnode,oldnode);
if(!file.open(QFile::WriteOnly|QFile::Truncate))
return;
//输出到文件
QTextStream out_stream(&file);
doc.save(out_stream,4); //缩进4格
file.close();
}
int main(int argc, char *argv[])
{
qDebug()<<"write xml to file...";
WriteXml(); //写xml
qDebug()<<"read xml to display...";
ReadXml(); //读xml
qDebug()<<"add contents to xml...";
AddXml(); //添加xml
qDebug()<<"remove contents from xml...";
RemoveXml(); //删除xml
qDebug()<<"update contents to xml...";
UpdateXml(); //更新xml
return 0;
}
写xml
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book id="1" time="2013/6/13">
<title>C++ primer</title>
<author>Stanley Lippman</author>
</book>
<book id="2" time="2007/5/25">
<title>Thinking in Java</title>
<author>Bruce Eckel</author>
</book>
</library>
增加xml
<?xml version='1.0' encoding='UTF-8'?>
<library>
<book time="2013/6/13" id="1">
<title>C++ primer</title>
<author>Stanley Lippman</author>
</book>
<book time="2007/5/25" id="2">
<title>Thinking in Java</title>
<author>Bruce Eckel</author>
</book>
<book time="1813/1/27" id="3">
<title>Pride and Prejudice</title>
<author>Jane Austen</author>
</book>
</library>
删除xml
<?xml version='1.0' encoding='UTF-8'?>
<library>
<book time="2013/6/13" id="1">
<title>C++ primer</title>
<author>Stanley Lippman</author>
</book>
<book time="2007/5/25" id="2">
<title>Thinking in Java</title>
<author>Bruce Eckel</author>
</book>
<book time="1813/1/27" id="3">
<title>Pride and Prejudice</title>
<author>Jane Austen</author>
</book>
</library>
更新xml
<?xml version='1.0' encoding='UTF-8'?>
<library>
<book id="1" time="2013/6/13">
<title>C++ primer</title>
<author>Stanley Lippman</author>
</book>
<book id="3" time="1813/1/27">
<title>Emma</title>
<author>Jane Austen</author>
</book>
</library>
示例2
#include "widget.h"
#include "ui_widget.h"
#include <QtXml>
#include <QFile>
#include <QFileDialog>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget),
m_carId(1)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_toolButton_clicked()
{
// 生成一个QT创建一些文本文件的类的对象, 如xml,world等。
QDomDocument carMessage;
// 这些代码是为了写xml文件头,m_carId这里是为了多次添加时,只写一次文件头。
if(1 == m_carId) {
QString strHeader( "version=\"1.0\" encoding=\"UTF-8\"" );
carMessage.appendChild( carMessage.createProcessingInstruction("xml", strHeader) );
}
// 这里的字符串容器保存的是后面需要用上的参数和内容。
QStringList carMessageNameList;
carMessageNameList << QString::fromUtf8("排量")
<< QString::fromUtf8("价格")
<< QString::fromUtf8("排放")
<< QString::fromUtf8("油耗")
<< QString::fromUtf8("功率");
QStringList carMessageParamList;
carMessageParamList << QString::fromUtf8("1000ml")
<< QString::fromUtf8("10万")
<< QString::fromUtf8("欧4")
<< QString::fromUtf8("5(km/时)")
<< QString::fromUtf8("74/6000");
//当一个xml创建后,是需要对应的元素的。无论是第几级,都是用这个类进行增加对应的item;如下面图中的<car>,<attrib>
QDomElement carNode = carMessage.createElement("car");
carNode.setAttribute("id", QString::number(m_carId));
for(int i = 1; i <= 5; ++i) {
//QDomText textNode用于写元素中间的内容,如:1000ml,10万等
QDomText textNode = carMessage.createTextNode(carMessageParamList.at(i - 1));
QDomElement attribNode = carMessage.createElement("attrib");
//这是每一级item对应的属性的增加,如id ="1",param ="排量"
attribNode.setAttribute("param", carMessageNameList.at(i - 1));
attribNode.appendChild(textNode);
carNode.appendChild(attribNode);
carMessage.appendChild(carNode);
}
//这里的功能是给用户手动选择一个地方保存,并如果在未填写后缀名时,默认加上后缀名
QString fileName = QFileDialog::getSaveFileName(this, "Save", QLatin1String("./testDome"), "*.xml");
if(!fileName.endsWith(QLatin1String("xml")))
fileName += QLatin1String(".xml");
//通过文本流的方式把添加的内容写xml文件中,QIODevice::Append方式为可以原文件内容上继续添加,不用清空原文件内容
QFile file(fileName);
if(!file.open(QIODevice::WriteOnly | QIODevice::Append))
return;
QTextStream stream(&file);
carMessage.save(stream, 4);
file.close();
++ m_carId;
}