下载TinyXml库,集成到Cococs2d-x工程中,编译运行,写测试代码,一切顺利!
可是CygWin编译,生成APK后,在Android真机上跑,程序崩溃!这可愁死人了!!!!!
于是,周末有空看了下Cocos2dx的源码.
发现Android下的文件都是从zip里面读取,所以给Tinyxml增加了一个方法 可以使它在android下正确读取xml文件.
1 /// Load Xml form memory buff. Returns true if successful. 2 bool TiXmlDocument::LoadMemory( const char * pBuff, int length, TiXmlEncoding encoding ) 3 { 4 if ( !pBuff || length == 0 ) 5 { 6 SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN ); 7 return false; 8 } 9 10 // If we have a file, assume it is all one big XML file, and read it in. 11 // The document parser may decide the document ends sooner than the entire file, however. 12 TIXML_STRING data; 13 data.reserve( length ); 14 15 char* buf = new char[ length+1 ]; 16 buf[0] = 0; 17 18 memcpy( buf, pBuff, length ); 19 20 const char* lastPos = buf; 21 const char* p = buf; 22 23 buf[length] = 0; 24 while( *p ) { 25 assert( p < (buf+length) ); 26 if ( *p == 0xa ) { 27 // Newline character. No special rules for this. Append all the characters 28 // since the last string, and include the newline. 29 data.append( lastPos, (p-lastPos+1) ); // append, include the newline 30 ++p; // move past the newline 31 lastPos = p; // and point to the new buffer (may be 0) 32 assert( p <= (buf+length) ); 33 } 34 else if ( *p == 0xd ) { 35 // Carriage return. Append what we have so far, then 36 // handle moving forward in the buffer. 37 if ( (p-lastPos) > 0 ) { 38 data.append( lastPos, p-lastPos ); // do not add the CR 39 } 40 data += (char)0xa; // a proper newline 41 42 if ( *(p+1) == 0xa ) { 43 // Carriage return - new line sequence 44 p += 2; 45 lastPos = p; 46 assert( p <= (buf+length) ); 47 } 48 else { 49 // it was followed by something else...that is presumably characters again. 50 ++p; 51 lastPos = p; 52 assert( p <= (buf+length) ); 53 } 54 } 55 else { 56 ++p; 57 } 58 } 59 // Handle any left over characters. 60 if ( p-lastPos ) { 61 data.append( lastPos, p-lastPos ); 62 } 63 delete [] buf; 64 buf = 0; 65 66 Parse( data.c_str(), 0, encoding ); 67 68 if ( Error() ) 69 { 70 return false; 71 } 72 73 return true; 74 }
传入一个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;
浙公网安备 33010602011771号