XML文件是一种文本格式的文件,其具体的格式可以看:https://www.cnblogs.com/stroll/p/7064503.html
经过查找,Qt对XML文件的操作主要有三种方法,通过QXmlStreamReader、QDomDocument、QXmlSimpleReader,其中QDomDocument操作简单方便,但是对于较大的文件可能会有问题,QXmlSimpleReader可以对大文件进行操作,但是其用方法相对于QDomDocument麻烦。
关于这三种方法的使用可以参考以下博客:https://www.cnblogs.com/albizzia/p/9152992.html,另外QXmlStreamReader还有一篇博客的汇总:http://www.cnblogs.com/lgxZJ/p/7966091.html
下面介绍下QDomDocument对XML的操作
读XML
QFile file(filePath);
if(!file.exists()) return false;
if(file.open(QIODevice::ReadOnly | QIODevice::Text)) return false;
QDomElement root = domdoc.documentElement(); //获取根节点
//下边遍历根节点下的子节点
QDomElement node = root.firstChildElement();
while(!node.isNull())
{
if(node.tagName() == "FeatrueSetting")
{
readXMLTable(node); //遍历每个node下的子节点
}
node = node.nextSiblingElement();
}
void Geo3DML2XDB::readXMLTable(QDomElement node)
{
ConfigStruct *tempXMLTableStruct = NULL;
tempXMLTableStruct = new ConfigStruct;
tempXMLTableStruct->_xdbName = node.attribute("XdbName");
tempXMLTableStruct->_3dmlName = node.attribute("Geo3dMLName");
node = node.firstChildElement();
while(!node.isNull())
{
if(node.tagName() == "Feild")
{
tempXMLTableStruct->_nameMaps[node.attribute("XdbName")] = node.attribute("Geo3dMLName");
}
node = node.nextSiblingElement();
}
_configInfo.push_back(tempXMLTableStruct);
}
其中还可以用QDomNode来替换QDomElement实现遍历,但是需要用到toElement()函数将QDomNode转为QDomElement
函数介绍:
QDomElement::tagName()返回元素名
QDomElement::attribute("XdbName")返回属性名为XdbName的属性值
QDomElement::Text()返回内容
写XML
void Geo3DML2XDB::saveToConfigFile()
{
QDomDocument doc;
QDomProcessingInstruction str = doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
doc.appendChild(str);
QDomElement root = doc.createElement("Settings");
doc.appendChild(root);
int i;
ConfigStruct *tempConfig = NULL;
for (i = 0; i < _configInfo.size(); i++)
{
tempConfig = _configInfo[i];
QDomElement feature = doc.createElement("FeatrueSetting");
feature.setAttribute("Geo3dMLName", tempConfig->_3dmlName);
feature.setAttribute("XdbName", tempConfig->_xdbName);
QMap<QString, QString>::Iterator iter;
for (iter = tempConfig->_nameMaps.begin(); iter != tempConfig->_nameMaps.end(); iter++)
{
QDomElement feild = doc.createElement("Feild");
feild.setAttribute("Geo3dMLName", iter.value());
feild.setAttribute("XdbName", iter.key());
feature.appendChild(feild);
}
root.appendChild(feature);
}
QByteArray xml = doc.toString().toUtf8();
QString filePath = QCoreApplication::applicationDirPath() + "/tpl.xml";
QFile savexml(filePath);
if(!savexml.open(QIODevice::WriteOnly | QIODevice::Text))
{
return;
}
savexml.write(xml);
savexml.close();
}