http://blog.sina.com.cn/s/blog_a6fb6cc90101eugv.html
关于XML及其使用场景不在此多做介绍,今天主要介绍Qt中对于XML的解析。QtXml模块提供了一个读写XML文件的流,解析方法包含DOM和SAX,两者的区别是什么呢?
SAX(Simple APIfor XML):接近于底层,速度较快,但不便于访问。
#include
QT += xml
Note that QXmlStream* classes are inQtCore,这句话是说QXmlStreamReader和QXmlStreamWriter不在模块QtXml中,而是在QtCore中,该模块只涉及DOM和SAX基于XML的接口。
此模块中包含的类不再多作介绍,详情请查看:
http://qt-project.org/doc/qt-4.8/qtxml.html
例子:
person.xml文件如下所示:
解析方法:
void ParseXML::parse(QString file_name)
{
if(file_name.isEmpty())
return;
QFile file(file_name);
if(!file.open(QFile::ReadOnly | QFile::Text))
{
QMessageBox::information(NULL,QString("title"),QString("open error!"));
return;
}
QDomDocument document;
QString error;
int row = 0,column = 0;
if(!document.setContent(&file,false,&error,&row,&column))
{
QMessageBox::information(NULL,QString("parse file Failed at line row and column") +QString::number(row,10) + QString(",") + QString::number(column,10));
return;
}
if(document.isNull())
{
QMessageBox::information(NULL,QString("document is null!"));
return;
}
QDomElement root =document.documentElement();
//root_tag_name为persons
QString root_tag_name =root.tagName();
if(root.hasAttribute("name"))
{
//name为Qt
QString name =root.attributeNode("name").value();
}
//获取id="1"的节点
QDomElement person =root.firstChildElement();
if(person.isNull())
return;
QString person_tag_name= person.tagName();
//id为1
QString id =person.attributeNode("id").value();
//获取子节点,数目为2
QDomNodeList list =root.childNodes();
int count =list.count();
for(int i=0; i
{
QDomNode dom_node = list.item(i);
QDomElement element =dom_node.toElement();
//获取id值,等价
QString id_1 =element.attributeNode("id").value();
QString id_2 = element.attribute("id");
QDomNodeList child_list =element.childNodes();
int child_count = child_list.count();
for(int j=0; j
{
QDomNodechild_dom_node = child_list.item(j);
QDomElement child_element = child_dom_node.toElement();
QStringchild_tag_name = child_element.tagName();
QStringchild__tag_value = child_element.text();
}
}
//按照name、age、email、website的顺序获取值
QDomElement element =person.firstChildElement();
while(!element.isNull())
{
QString tag_name = element.tagName();
QString tag_value = element.text();
element = element.nextSiblingElement();
}
}