网上的例子大多是简单的例子的使用,但是对于多层次的或是未知层次的没有相应的记录。自己写了一个QT版的遍历XML的类NodeIterator
nodeiterator.h文件
#ifndef NODEITERATOR_H
#define NODEITERATOR_H
#include <QDomDocument>
class NodeIterator
{
public:
NodeIterator();
NodeIterator(QDomNode root);
bool hasNext();
QDomNode next();
private:
QDomNode root, current;
bool isHasNext;
};
#endif // NODEITERATOR_Hnodeiterator.cpp文件
#include "nodeiterator.h"
NodeIterator::NodeIterator()
{
}
NodeIterator::NodeIterator(QDomNode root)
{
this->root = root;
current = root;
}
bool NodeIterator::hasNext(){
if (!root.isNull()) {
//是否当前节点有子节点
if (!current.isNull() && current.hasChildNodes()) {
//将第一个子节点变成当前节点
current = current.firstChildElement();
isHasNext = true;
} else if (!current.isNull()&& !current.nextSiblingElement().isNull()) {
current = current.nextSiblingElement();
isHasNext = true;
} else if (!current.isNull()) {
while (!current.isNull() && current != root && current.nextSiblingElement().isNull()) {
current = current.parentNode();
}
if (!current.isNull() && current != root) {
current = current.nextSiblingElement();
isHasNext = true;
} else {
isHasNext = false;
}
} else {
isHasNext = false;
}
} else {
isHasNext = false;
}
return isHasNext;
}
QDomNode NodeIterator::next() {
return current;
}有了这个类就可以根据名称检索相应的节点
QFile *file=new QFile("D:/qt project/SymbolEdit/symbol.xml");
if( !file->open(QFile::ReadOnly)){
qDebug()<<"open file Failed ";
return;
}
QDomDocument *document=new QDomDocument;
QString strError;
int errLin = 0, errCol = 0;
if( !document->setContent(file, false, &strError, &errLin, &errCol) ) {
printf( "parse file Failed\n");
return;
}
if( document->isNull() ) {
printf( "document is null !\n" );
return;
}
QDomElement root = document->documentElement();
//QIterator<Node>
if (!root.isNull()) {
QDomNode current;
QString name , epTypeAlisaName ;
for (NodeIterator *it = new NodeIterator((QDomNode)root); it->hasNext();) {
current = it->next();
if (!current.isNull() && current.isElement()) {
name = current.nodeName();
//如果是电力图元的节点
if (!name.isNull() && name=="epType") {
epTypeAlisaName = current.toElement().attribute("alisaname");
QString electricType = current.toElement().attribute("electricType");
epTypeAlisaNames->append(epTypeAlisaName);
epTypeAlisaNameToElectricTypeName->insert(epTypeAlisaName,electricType);
}
}
}
}原文链接:https://www.f2er.com/xml/297161.html