QDomDocument doc; //新建QDomDocument类对象,它代表一个XML文档
QFile file("my.xml"); //建立指向"my.xml"文件的QFile对象
if (!file.open(QIODevice::ReadOnly)) return 0; //以只读方式打开
if (!doc.setContent(&file)) //将文件内容读到doc中
{
file.close();
return 0;
}
file.close();
QDomNode firstNode = doc.firstChild(); //获得doc的第一个节点,即XML说明
qDebug() << firstNode.nodeName() //输出XML说明
<< firstNode.nodeValue();
QDomElement docElem = doc.documentElement(); //返回根元素
QDomNode n = docElem.firstChild(); //返回根节点的第一个子节点
while(!n.isNull())
{ //如果节点不为空
if (n.isElement()) //如果节点是元素
{
QDomElement e = n.toElement(); //将其转换为元素
qDebug() << qPrintable(e.tagName()) //返回元素标记
<< qPrintable(e.attribute("id")); //返回元素id属性的值
}
n = n.nextSibling(); //下一个兄弟节点
}
//XML文件操作
QFile file("my.xml");
if(!file.open(QIODevice::WriteOnly | QIODevice::Truncate))
return ; //只写方式打开,并清空以前的信息
QDomDocument doc;
QDomProcessingInstruction instruction;
//添加处理指令
instruction = doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
doc.appendChild(instruction);
QDomElement root = doc.createElement(QStringLiteral("书库"));
doc.appendChild(root); //添加根元素
//添加第一个book元素及其子元素
QDomElement book = doc.createElement(QStringLiteral("图书"));//添加图书节点
QDomAttr id = doc.createAttribute(QStringLiteral("编号"));//添加编号属性,属性位于节点后面
QDomElement title = doc.createElement(QStringLiteral("书名"));//添加书名节点
QDomElement author = doc.createElement(QStringLiteral("作者"));//添加作者节点
QDomText text;
id.setValue(QStringLiteral("1"));//id置1
book.setAttributeNode(id);
text = doc.createTextNode(QStringLiteral("Qt"));//创建内容节点
title.appendChild(text);//书名节点添加数据
text = doc.createTextNode(QStringLiteral("shiming"));//创建内容节点
author.appendChild(text);//作者节点添加数据
book.appendChild(title);//图书节点添加书名节点
book.appendChild(author);//图书节点添加作者节点
root.appendChild(book); //添加第二个book元素及其子元素
QTextStream out1(&file);//创建文本流
doc.save(out1,4); //将文档保存到文件,4为子元素缩进字符数
file.close();
//查看XML
ui->listWidget->clear(); //先清空显示
QFile file(“my.xml”);
if (!file.open(QIODevice::ReadOnly))
return ;
QDomDocument doc;
if (!doc.setContent(&file))
{
file.close();
return ;
}
file.close(); //返回根节点及其子节点的元素标记名
QDomElement docElem = doc.documentElement(); //返回根元素
QDomNode n = docElem.firstChild(); //返回根节点的第一个子节点
while(!n.isNull()) //如果节点不为空
{
if (n.isElement()) //如果节点是元素
{
QDomElement e = n.toElement(); //将其转换为元素
ui->listWidget->addItem(e.tagName()+e.attribute(tr("编号")));
QDomNodeList list = e.childNodes();
for(int i=0; i<list.count(); i++)
{
QDomNode node = list.at(i);
if(node.isElement()) ui->listWidget->addItem(" "+node.toElement().tagName() +":"
+node.toElement().text());
}
}
n = n.nextSibling(); //下一个兄弟节点
}