Android下使用TinyXml读取xml配置文件(Cocos2d-x游戏开发)
转载请保留原地址http://www.cocos2dres.com/post/88.html谢谢!!!
下载TinyXml库,集成到Cococs2d-x工程中,编译运行,写测试代码,一切顺利!
可是CygWin编译,生成APK后,在Android真机上跑,程序崩溃!这可愁死人了!!!!!
于是,周末有空看了下Cocos2dx的源码.
发现Android下的文件都是从zip里面读取,所以给Tinyxml增加了一个方法 可以使它在android下正确读取xml文件.
[html]view plaincopy
///LoadXmlformmemorybuff.Returnstrueifsuccessful.
boolTiXmlDocument::LoadMemory(constchar*pBuff,intlength,TiXmlEncodingencoding)
{
if(!pBuff||length==0)
{
SetError(TIXML_ERROR,0,0,TIXML_ENCODING_UNKNOWN);
returnfalse;
}
//Ifwehaveafile,assumeitisallonebigXMLfile,andreaditin.
//Thedocumentparsermaydecidethedocumentendssoonerthantheentirefile,however.
TIXML_STRINGdata;
data.reserve(length);
char*buf=newchar[length+1];
buf[0]=0;
memcpy(buf,pBuff,length);
constchar*lastPos=buf;
constchar*p=buf;
buf[length]=0;
while(*p){
assert(p<(buf+length));
if(*p==0xa){
//Newlinecharacter.Nospecialrulesforthis.Appendallthecharacters
//sincethelaststring,andincludethenewline.
data.append(lastPos,(p-lastPos+1));//append,includethenewline
++p;//movepastthenewline
lastPos=p;//andpointtothenewbuffer(maybe0)
assert(p<=(buf+length));
}
elseif(*p==0xd){
//Carriagereturn.Appendwhatwehavesofar,then
//handlemovingforwardinthebuffer.
if((p-lastPos)>0){
data.append(lastPos,p-lastPos);//donotaddtheCR
}
data+=(char)0xa;//apropernewline
if(*(p+1)==0xa){
//Carriagereturn-newlinesequence
p+=2;
lastPos=p;
assert(p<=(buf+length));
}
else{
//itwasfollowedbysomethingelse...thatispresumablycharactersagain.
++p;
lastPos=p;
assert(p<=(buf+length));
}
}
else{
++p;
}
}
//Handleanyleftovercharacters.
if(p-lastPos){
data.append(lastPos,p-lastPos);
}
delete[]buf;
buf=0;
Parse(data.c_str(),0,encoding);
if(Error())
{
returnfalse;
}
returntrue;
}
传入一个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;
更多相关文章
- Unexpected namespace prefix "xmlns" found for tag LinearLayo
- OpenCore 的代码结构
- Android创建文件夹
- 图解Android源代码下载指南
- android 数据库技术 | 文件系统,SDCARD访问,CONTENT PROVIDER,SQLIT
- Android studio 使用心得(六)---android studio 如何加载.so文件
- 编写Android中直接可运行的二进制文件