一、Qt写XML文件
1.准备xml文件
QFile file("my.xml");
if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate))
return;
2.准备QDomDocument对象doc
QDomDocument doc;
3.准备QDomProcessingInstruction处理指令对象instruction,使用QDomDocument的createProcessingInstruction创建指令,并使用QDomDocument的appendChild, 将指令添加到doc中
QDomProcessingInstruction instruction;
instruction = doc.createProcessingInstruction("xml","version=\"1.0\"encoding=\"utf-8\"");
doc.appendChild(instruction);
4.使用QDomDocument的createElement创建根元素,使用QDomDocument的appendChild, 将根元素添加到doc中
QDomElement root = doc.createElement(tr("library")); //根元素的值为library
doc.appendChild(root);
5.为根元素root添加子元素
QDomElement book = doc.createElement(tr("book")); //根元素的子元素book
QDomAttr id = doc.createAttribute(tr("id")); //创建属性
id.setValue(tr("1")); //设置属性的值
book.setAttributeNode(id); //将属性添加到子元素book中
6.为元素book添加子元素及设置值,并将子元素添加到book元素中
QDomElement title = doc.createElement(tr("title")); //创建book的子元素title
QDomText text;
text = doc.createTextNode(tr("Qt")); //创建节点文本
title.appendChild(text); //将文本设置为title子项
QDomElement author = doc.createElement(tr("author"));
text = doc.createTextNode(tr("shiming"));
author.appendChild(text);
book.appendChild(title);
book.appendChild(author);
7.将book添加到根元素root中
root.appendChild(book);
//同理添加第二个book子元素
8.保存文档
QTextStream out(&file);
doc.save(out,4); // 将文档保存到文件,4为子元素缩进字符数
file.close();
二、Qt读XML文件
1.打开xml文件
QFile file("my.xml");
if (!file.open(QIODevice::ReadOnly))
return;
2.准备QDomDocument对象doc
QDomDocument doc;
3.将文档内容读出到doc中
if (!doc.setContent(&file))
{
file.close();
return;
}
file.close();
//遍历文档内容
QDomElement docElem = doc.documentElement(); //返回根元素
qDebug() << docElem.tagName(); //library
QDomNode n = docElem.firstChild(); //返回根节点的第一个子节点
while (!n.isNull()) //如果节点不为空
{
if (n.isElement()) //如果节点是元素
{
QDomElement e = n.toElement(); //转换为元素
qDebug() << e.tagName();
QDomNodeList list = e.childNodes();
for (int i = 0; i < list.count(); i++)
{
QDomNode node = list.at(i);
if (node.isElement())
qDebug() << node.toElement().tagName() + ":" + node.toElement().text(); }
}
n = n.nextSibling(); //下一个兄弟节点
}