您的位置:首页 > 编程语言 > Qt开发

QT 遍历多层次的XML文档

2015-02-28 16:50 267 查看
网上的例子大多是简单的例子的使用,但是对于多层次的或是未知层次的没有相应的记录。自己写了一个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_H

nodeiterator.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);


}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: