依赖的头文件:
#include
#include
#include
#include
#include
示例代码:
//写xml操作。sXmlFilePath:要写入的xml文件路径
int CAppletGenerator::addTaskMenuTreeItem(QString sXmlFilePath)
{
QFile file(sXmlFilePath);
if (!file.open(QFile::ReadOnly | QFile::Text)) {
return -1;
}
QDomDocument domDocument;
if (!domDocument.setContent(&file, true)) {
file.close();
return -1;
}
QDomElement tree = domDocument.documentElement();
QDomElement firstItem = tree.firstChildElement();
//在firstitem上添加一个节点
QDomElement secondItem = domDocument.createElement("item");
//获取当前时间,用于节点的唯一性id
QDateTime dt;
QTime time;
QDate date;
dt.setTime(time.currentTime());
dt.setDate(date.currentDate());
QString currentDate = dt.toString("yyyyMMddhhmmss");
//为节点添加属性
secondItem.setAttribute("id",currentDate);
secondItem.setAttribute("select","1");
secondItem.setAttribute("text","节点");
//添加元素节点到父节点
firstItem.appendChild(secondItem);
file.close();
QFile fileModify(sXmlFilePath);
if (!fileModify.open(QFile::WriteOnly | QFile::Text)){
return -1;
}
//核心代码:Dom方式写xml文件
QTextStream out(&fileModify);
domDocument.save(out,4);
fileModify.close();
return 0;
}