1.写入xml文档中
bool protProjectInfo::SaveXml()
{
//QFile file(mProjectInfoPath.filePath("projectconfig.xml"));
QFile file("c:/projectconfig.xml");
if(! file.open(QIODevice::WriteOnly)) {
//logger()->error("open file fail '%1'.",mProjectInfoPath.filePath("projectconfig.xml"));
file.close();
return false;
}
QDomDocument projectinfodom;
projectinfodom.appendChild( projectinfodom.createProcessingInstruction("xml","version="1.0" encoding="UTF-8""));
QDomElement projectelement = projectinfodom.createElement("Project");
projectinfodom.appendChild(projectelement);
QDomElement projectnameelement = projectinfodom.createElement("ProjectName");
projectnameelement.appendChild(projectinfodom.createTextNode(mProjectName));
projectelement.appendChild(projectnameelement);
QDomElement createtimeelement = projectinfodom.createElement("CreateTime");
createtimeelement.appendChild(projectinfodom.createTextNode(mCreateTime.toString("yyyy/MM/dd hh:mm:ss")));
projectelement.appendChild(createtimeelement);
QTextStream stream(&file);
projectinfodom.save(stream,4);
file.close();
return true;
}
2.读xml文件
bool protProjectInfo::LoadXml()
{
//QFile file(mProjectInfoPath.filePath("projectconfig.xml"));
QFile file("c:/projectconfig.xml");
if(! file.open(QIODevice::ReadOnly)) {
//logger()->error("Open '%1' failed,'%2'.",mProjectInfoPath.filePath("projectconfig.xml"),file.errorString());
return false;
}
QDomDocument doc;
if (! doc.setContent(&file,true)) {
//logger()->error("QDomDocument setContent fail.");
file.close();
return false;
}
file.close();
QDomElement docrootelement = doc.documentElement();
QDomElement projectnameelement = docrootelement.firstChildElement("ProjectName");
QDomElement createtimeelement = docrootelement.firstChildElement("CreateTime");
mProjectName = projectnameelement.text();
mCreateTime = QDateTime::fromString(createtimeelement.text(),"yyyy/MM/dd hh:mm:ss");
return true;
}
3.注意事项
1.protProjectInfo 是个简单类
QDir mProjectInfoPath;
QString mProjectName;
QDateTime mCreateTime;
2.xml格式如下
<?xml version="1.0" encoding="UTF-8"?>
<Project>
<ProjectName>project09</ProjectName>
<CreateTime>2015/07/22 16:22:05</CreateTime>
</Project>
QFile file("c:/projectconfig.xml");