Qt的xml模块,需要在pro文件中加入QT += xml,头文件为QDomDocument
//创建xml文件
{
QDomDocument doc;
QDomProcessingInstruction instruction; //XML说明
instruction = doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\""); //XML说明
doc.appendChild(instruction); //doc第一次填加,即加在了文件开头
QDomElement rroot;
QDomElement root;
QDomElement child;
QDomText text;
rroot = doc.createElement(QString::fromUtf8("目录")); //一级节点(根)
doc.appendChild(rroot);
root = doc.createElement(QString::fromUtf8("分类")); //二级节点
root.setAttribute("attr","value"); //设置节点属性以及属性值
rroot.appendChild(root);
child = doc.createElement(QString::fromUtf8("藏书"));//三级节点
text = doc.createTextNode(QString::fromUtf8("编程入门"));//节点内容
child.appendChild(text);
root.appendChild(child);
child = doc.createElement(QString::fromUtf8("类别"));//三级节点
text = doc.createTextNode(QString::fromUtf8("语言"));//节点内容
child.appendChild(text);
root.appendChild(child);
root = doc.createElement(QString::fromUtf8("地址")); //二级节点
rroot.appendChild(root);
child = doc.createElement(QString::fromUtf8("省份")); //三级节点
text = doc.createTextNode(QString::fromUtf8("江苏")); //节点内容
child.appendChild(text);
root.appendChild(child);
QFile file("BookConfig.xml");
if(!file.open(QIODevice::Truncate | QIODevice::WriteOnly))
{
return;
}
QTextStream out(&file);
doc.save(out, 4); //4为子元素缩进符
file.close();
}
//读取xml文件
{
QFile file("BookConfig.xml");
if(!file.exist())
return;
if(!file.open(QIODevice::ReadOnly))
return;
QDomDocument doc;
if (!doc.setContext(&file)) //xml文档类包含文件内容
{
file.close();
return;
}
file.close(); //此时文件句柄已经不需要了,关闭
QDomNodeList list = doc.elementsByTagName("分类"); //获取"分类"的节点列表
QDomAttr attr = list.at(0).toElement().attributeNode("attr");
qDebug() << attr.value(); //打印"value",获取节点属性值
QDomNodeList child = list.at(0).childNodes(); //获取"分类"节点下的子节点列表
for (int i = 0; i < child.count(); i++)
{
qDebug() << child.at(i).toElement().tagName(); //获取子节点名字
qDebug() << child.at(i).toElement().text(); //获取子节点内容
qDebug() << "----------";
}