xml文件部分:
<?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;
}