Qt解析xml

         发现用 Qt 解析 xml 文件非常方便,下面是一个简单的解析 xml 文件的例子:

#include <QtCore/QCoreApplication>
#include <QDomDocument>
#include <QDomElement>
#include <QDomAttr>
#include <QFile>

void parse( const char *filename )
{
	if( NULL == filename )
		return;

	QFile file( filename );
	if( !file.open(QFile::ReadOnly | QFile::Text) ) {
		printf( "open file '%s' failed, error: %s !\n", filename, file.errorString().toStdString().c_str() );
		return;
	}

	QDomDocument	document;
	QString			strError;
	int				errLin = 0, errCol = 0;
	if( !document.setContent(&file, false, &strError, &errLin, &errCol) ) {
		printf( "parse file failed at line %d column %d, error: %s !\n", errLin, errCol, strError );
		return;
	}

	if( document.isNull() ) {
		printf( "document is null !\n" );
		return;
	}

	QDomElement root = document.documentElement();
	printf( "%s ", root.tagName().toStdString().c_str() );
	if( root.hasAttribute("name") )
		printf( "%s\n", root.attributeNode("name").value().toStdString().c_str() );

	QDomElement files = root.firstChildElement();
	if( files.isNull() )
		return;
	else
		printf( "\t%s\n", files.tagName().toStdString().c_str() );

	QDomElement element = files.firstChildElement();
	while( !element.isNull() ) {
		if( element.hasAttribute("name") )
			printf( "\t\t file: %s", element.attributeNode("name").value().toStdString().c_str() );
		if( element.hasAttribute("size") )
			printf( "\t %s", element.attributeNode("size").value().toStdString().c_str() );
		printf( "\n" );
		element = element.nextSiblingElement();
	}
}

int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);

	char filename[256] = { 0 };
	printf( "please input file name: " );
	gets( filename );

	parse( filename );

	return a.exec();
}


执行效果:

xml文件:

 

这个只是 xml 文件解析的例子,xml 文件的生存还没有研究过,以后有时间再说。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值