转载请保留原地址 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;