qt解析xml文件

一、打开文件

void ABC::openXml()  //打开XML文件

{ 
 QFile xmlFile("./xml/menu.xml"); 
 if(!xmlFile.open(QIODevice::ReadOnly)) 
 { 
 qDebug("不能打开文件!"); 
 return ; //不能打开文件 
 } 
 QDomDocument doc; 
 if (!doc.setContent(&xmlFile)) 
 { 
 qDebug("不能加载文件!"); 
 xmlFile.close(); 
 return; 
 } 
 this->readXmlMenu(doc); 
} 
 

二、解析菜单类型

 void ABC::readXmlMenu(QDomDocument doc) //解析菜单类型 
{ 
 QDomElement root = doc.documentElement(); 
 QDomNodeList nodelist = root.childNodes(); 
 for(unsigned i = 0; i < nodelist.length(); ++i) 
 { 
  QString title = nodelist.item(i).toElement().attribute("title"); 
 if(! title.isEmpty()) 
 { 
 treeMenu = new QTreeWidget(treeFrame); 
 treeMenu->setGeometry(0, i*150, 180, 150); 
 treeMenu->setColumnCount(1); 
 QStringList headers; 
 headers << title; 
 treeMenu->setHeaderLabels(headers); //设置标题 
 treeMenu->insertTopLevelItems(0, rootList); 
 this->readXmlItem(nodelist.item(i), treeMenu); 
 } 
 } 
} 
三、解析子菜单 
void ABC::readXmlItem(QDomNode node, QTreeWidget *treeItem) //解析菜单子级 
 
 
{  
 QDomNodeList nodelist = node.childNodes(); 
 for(unsigned i = 0; i < nodelist.length(); ++i) 
 { 
 QString title = nodelist.item(i).toElement().attribute("title"); 
 if(nodelist.item(i).toElement().attribute("isend") == "false") 
 { 
 rootItem = new QTreeWidgetItem(treeItem, QStringList(QString(title))); 
 rootList << rootItem; 
 treeMenu->expandAll(); //全部显示 
 this->readXmlItem(nodelist.item(i), treeItem); 
 } 
 else 
 { 
 QTreeWidgetItem *leaf = new QTreeWidgetItem(rootItem, QStringList(QString(title))); 
 rootItem->addChild(leaf); 
 } 
 } 
} 
四、xml文件 
<?xml version="1.0" encoding="utf-8"?> <menu> 
<menuType id="1" title="手机"> <listItem title="正在建设中..." isend = "false" url=""></listItem> </menuType> <menuType id="1" title="网络"> <listItem title="正在建设中..." isend = "false" url=""></listItem> </menuType> 
</menu> 

你可能感兴趣的:(qt解析xml文件)