引言
这篇文章与其说是xml文件的更新,不如说是修改xml文件中之前的某些值。
示例
该文章依旧是基于之前的读写xml文章的基础,找到xml文件中每个节点的ip,查找最新的数据中是否含有xml文件中该节点的ip,有 则更新其名称和id.
void Config::updateKvmSeatXmlInfo(QMap<QString, stuSeatInfo> &updateSeatSet)
{m_updateSeatSet = updateSeatSet;QString strPath = getExeFilePath();strPath += strKvmConfigFileName;QFile file(strPath);if (!file.open(QIODevice::ReadOnly)) {qDebug()<<QStringLiteral("打开")<<strPath<<QStringLiteral("文件失败!");return;}QDomDocument doc;if (!doc.setContent(&file)) {qDebug()<<QStringLiteral("文件")<<strPath<<QStringLiteral("解析失败!");file.close();return ;}file.close();QDomElement root = doc.documentElement();//获取根节点QDomNode node = root.firstChild();//根节点的第一个子节点if (!node.isNull()) {if (node.isElement()) {QDomElement element = node.toElement();if (element.tagName() == QString("seatInfo")) {updateSeatXmlInfo(element);}}}QString strXml = doc.toString();qDebug()<<QStringLiteral("更新后席位信息:")<<strXml;QFile exitFile(strPath);if (!exitFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {qDebug()<<QStringLiteral("打开")<<strPath<<QStringLiteral("文件失败!");return;}QTextStream out(&exitFile);doc.save(out,4,QDomNode::EncodingFromDocument);//此处也可以写为out<<strXml;只不过格式没有缩进,含有中文的处理exitFile.close();
}void Config::updateSeatXmlInfo(QDomElement &element)
{QMap<QString,stuSeatInfo>::iterator it;QDomNodeList nodeList = element.childNodes();for (int i = 0; i < nodeList.size(); ++i) {for (it = m_updateSeatSet.begin(); it != m_updateSeatSet.end(); ++it) {QDomNodeList seatNode = nodeList.at(i).childNodes();QString seatIp = seatNode.at(3).toElement().firstChild().nodeValue();if (seatIp == it.key()) {QString strSeatName = seatNode.at(1).toElement().firstChild().nodeValue();QString strSeatId = seatNode.at(2).toElement().firstChild().nodeValue();if (it.value().seatName.compare(strSeatName) != 0) {seatNode.at(1).toElement().firstChild().setNodeValue(it.value().seatName);}if (it.value().seatId.compare(strSeatId) != 0) {seatNode.at(2).toElement().firstChild().setNodeValue(it.value().seatId);}break;}}}
}
该文章写的可能不太好理解,原读者都能懂吧。