Android下使用TinyXml读取xml配置文件(Cocos2d-x游戏开发)

转载请保留原地址 http://www.cocos2dres.com/post/88.html 谢谢!!!

下载TinyXml库,集成到Cococs2d-x工程中,编译运行,写测试代码,一切顺利!

可是CygWin编译,生成APK后,在Android真机上跑,程序崩溃!这可愁死人了!!!!!

于是,周末有空看了下Cocos2dx的源码.
发现Android下的文件都是从zip里面读取,所以给Tinyxml增加了一个方法 可以使它在android下正确读取xml文件.

/// Load Xml form memory buff. Returns true if successful.
bool TiXmlDocument::LoadMemory( const char * pBuff, int length, TiXmlEncoding encoding )
{
	if ( !pBuff || length == 0 ) 
	{
		SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN );
		return false;
	}

	// If we have a file, assume it is all one big XML file, and read it in.
	// The document parser may decide the document ends sooner than the entire file, however.
	TIXML_STRING data;
	data.reserve( length );

	char* buf = new char[ length+1 ];
	buf[0] = 0;

	memcpy( buf, pBuff, length );

	const char* lastPos = buf;
	const char* p = buf;

	buf[length] = 0;
	while( *p ) {
		assert( p < (buf+length) );
		if ( *p == 0xa ) {
			// Newline character. No special rules for this. Append all the characters
			// since the last string, and include the newline.
			data.append( lastPos, (p-lastPos+1) );	// append, include the newline
			++p;									// move past the newline
			lastPos = p;							// and point to the new buffer (may be 0)
			assert( p <= (buf+length) );
		}
		else if ( *p == 0xd ) {
			// Carriage return. Append what we have so far, then
			// handle moving forward in the buffer.
			if ( (p-lastPos) > 0 ) {
				data.append( lastPos, p-lastPos );	// do not add the CR
			}
			data += (char)0xa;						// a proper newline

			if ( *(p+1) == 0xa ) {
				// Carriage return - new line sequence
				p += 2;
				lastPos = p;
				assert( p <= (buf+length) );
			}
			else {
				// it was followed by something else...that is presumably characters again.
				++p;
				lastPos = p;
				assert( p <= (buf+length) );
			}
		}
		else {
			++p;
		}
	}
	// Handle any left over characters.
	if ( p-lastPos ) {
		data.append( lastPos, p-lastPos );
	}		
	delete [] buf;
	buf = 0;

	Parse( data.c_str(), 0, encoding );

	if (  Error() )
	{
		return false;
	}
	
	return true;
}

传入一个buff,然后交给TineXml解析。

 

使用示例:

 TiXmlDocument* pXMLDoc = new TiXmlDocument( szSchemeName );

 unsigned long nLength = 0;
 char* pBuff = (char*)cocos2d::CCFileUtils::sharedFileUtils()->getFileData(cocos2d::CCFileUtils::sharedFileUtils()->fullPathFromRelativePath(szSchemeName),"rt", &nLength );

 pXMLDoc->LoadMemory( pBuff, nLength );

 SAFE_DELARR( pBuff );

 

.... 你的代码在这里

 

delete pXMLDoc;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值