16,240
社区成员
发帖
与我相关
我的任务
分享
<?xml version='1.0' encoding='GB2312'?>
<students>
<student id="1" name="张三" age="20"/>
<student id="2" name="李四" age="21"/>
</students>
struct XMLItem
{
int id;
QString name;
int age;
};
//! 读取一条记录
bool ReadItemFromXML(XMLItem & item)
{
// 打开xml文件
QFile file("D:\\test.xml");
if(!file.open(QIODevice::ReadOnly))
{
file.close();
return false;
}
QDomDocument doc;
QDomElement eleRoot;
if(!doc.setContent(&file))
{
file.close();
return false;
}
file.close();
// 查询记录
eleRoot = doc.documentElement();
QDomNodeList stunodes = doc.elementsByTagName("student");
if(stunodes.count() > 0)
{
for(int i = 0; i < stunodes.count(); i++)
{
if(stunodes.at(i).toElement().attribute("id").toInt() == item.id)
{
item.name = stunodes.at(i).toElement().attribute("name");
item.age = stunodes.at(i).toElement().attribute("age").toInt();
return true;
}
}
}
return false;
}
//! 删除一条记录
bool RemoveItemFromXML(XMLItem & item)
{
// 打开xml文件
QFile file("D:\\test.xml");
if(!file.open(QIODevice::ReadWrite))
{
file.close();
return false;
}
// 如果该文件为空文件,则添加xml文件头
QDomDocument doc;
QDomElement eleRoot;
if(file.atEnd())
{
QDomProcessingInstruction instruction;
instruction = doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"GB2312\"");
doc.appendChild(instruction);
eleRoot = doc.createElement("students");
doc.appendChild(eleRoot);
}
else
{
// 文件不为空,则设为document的内容
if(!doc.setContent(&file))
{
file.close();
return false;
}
// 删除记录
eleRoot = doc.documentElement();
QDomNodeList stunodes = doc.elementsByTagName("student");
if(stunodes.count() > 0)
{
for(int i = 0; i < stunodes.count(); i++)
{
if(stunodes.at(i).toElement().attribute("id").toInt() == item.id)
{
eleRoot.removeChild(stunodes.at(i));
break;
}
}
}
}
file.close();
// 重新写入xml文件
file.open(QIODevice::Truncate| QIODevice::WriteOnly);
QTextStream out(&file);
doc.save(out, 4);
file.close();
return true;
}
//! 插入一条记录
bool SaveItemToXML(XMLItem & item)
{
//删除相同id记录
RemoveFilterFromXML(item);
// 打开xml文件
QFile file("D:\\test.xml");
if(!file.open(QIODevice::ReadWrite))
{
file.close();
return false;
}
QDomDocument doc;
if(!doc.setContent(&file))
{
file.close();
return false;
}
file.close();
QDomElement eleRoot = doc.documentElement();
// 添加当前过滤项
QDomElement eleStu = doc.createElement("student");
eleStu.setAttribute("id", QString::number(item.id));
eleStu.setAttribute("name", item.name);
eleStu.setAttribute("age", QString::number(item.age));
eleRoot.appendChild(eleStu);
// 重新写入xml文件
file.open(QIODevice::Truncate| QIODevice::WriteOnly);
QTextStream out(&file);
doc.save(out, 4);
file.close();
return true;
}