Qt QtXml读取xml文件内容
xml文件内容
<?xml version="1.0" encoding="UTF-8"?> <YG_RTLS> <Anchor_list> <Anchor z="0" id="1" MA_ID="" y="1789" x="50" ant_dly="" type="2"/> <Anchor z="0" id="2" MA_ID="" y="1840" x="2970" ant_dly="" type="2"/> <Anchor z="0" id="3" MA_ID="" y="70" x="2940" ant_dly="" type="2"/> <Anchor z="0" id="4" MA_ID="" y="9" x="-19" ant_dly="" type="2"/> </Anchor_list> <Anchor_Group id="1" map_id="0" type="2"> <Member id="1"/> <Member id="2"/> <Member id="3"/> <Member id="4"/> </Anchor_Group> <CONFIG version="1"/> </YG_RTLS>
//读取基站配置文件数据 void readSysConfigFileData(QString sysConfigFileName) { //打开或创建文件 QFile xmlFile(sysConfigFileName); if (!xmlFile.open(QFile::ReadOnly)) { return; } QDomDocument docXML; if (!docXML.setContent(&xmlFile)) { xmlFile.close(); return; } xmlFile.close(); QDomElement xmlRoot = docXML.documentElement(); //返回根节点 QDomNode domNode = xmlRoot.firstChild(); //获得第一个子节点 while (!domNode.isNull()) //如果节点不空 { if (domNode.isElement()) //如果节点是元素 { QDomElement domElement = domNode.toElement(); //转换为元素,注意元素和节点是两个数据结构,其实差不多 QDomNodeList list = domElementchildNodes(); for (int i = 0; i<list.count(); i++) //遍历子元素,count和size都可以用,可用于标签数计数 { QDomNode nodeIndex = list.at(i); if (domNode.isElement()) { QDomElement indexElement = nodeIndex.toElement(); if (indexElement.hasAttribute("x")) { qDebug() << nodeIndex.nodeName() << ":" << nodeIndex.toElement().attribute("id") << " " << nodeIndex.toElement().attribute("x") << " " << nodeIndex.toElement().attribute("y") << " " << nodeIndex.toElement().attribute("z"); } } } } //下一个兄弟节点,nextSiblingElement()是下一个兄弟元素 domNode = domNode.nextSibling(); } }
输出
"Anchor" : "1" "50" "1789" "0"
"Anchor" : "2" "2970" "1840" "0"
"Anchor" : "3" "2940" "70" "0"
"Anchor" : "4" "-19" "9" "0"