前一阵子使用Tinyxml在安卓下读取xml文件的时候总是失败, 周末有空看了下Cocos2dx的源码.
发现Android下的文件都是从zip里面读取,所以给Tinyxml增加了一个方法 可以使它在android下正确读取xml文件.
在tingxml.cpp里面增加如下的方法即可:
bool TiXmlDocument::LoadFileByCocos2d( const char * filename, TiXmlEncoding encoding /*= TIXML_ENCODING_UTF8*/ )
{
if ( !filename )
{
SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
return false;
}
// Delete the existing data:
Clear();
location.Clear();
// Get the file size, so we can pre-allocate the string. HUGE speed impact.
const char *pfilePath = CCFileUtils::fullPathFromRelativePath(filename);
TIXML_STRING __filename( pfilePath );
value = __filename;
CCFileData data(pfilePath, "rt");
long length = data.getSize();
char *pBuffer = (char*) data.getBuffer();
if (!pBuffer)
{
SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
return false;
}
// Strange case, but good to handle up front.
if ( length <= 0 )
{
SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
return false;
}
const char* p = pBuffer; // the read head
char* q = pBuffer; // the write head
const char CR = 0x0d;
const char LF = 0x0a;
pBuffer = 0;
while( *p ) {
assert( p < (pBuffer+length) );
assert( q <= (pBuffer+length) );
assert( q <= p );
if ( *p == CR ) {
*q++ = LF;
p++;
if ( *p == LF ) { // check for CR+LF (and skip LF)
p++;
}
}
else {
*q++ = *p++;
}
}
assert( q <= (pBuffer+length) );
*q = 0;
Parse( pBuffer, 0, encoding );
return !Error();
}
其实非常简单, 就是修改了它原来打开文件的方式, 通过 CCFileData 来打开~
附件是Tinyxml的源代码, 包含了我增加的方法.
用法很简单:
假设有Test.xml文件 内容如下:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<RECORDS>
<RECORD m_ui32ID="1" m_strName="KuMo Test"/><RECORD m_ui32ID="2" m_strName="KuMo Test !"/>
</RECORDS>
读取代码如下 非常简单!:
void testxml(map<string, string>& M_Map)
{
TiXmlDocument* xmlDoc = new TiXmlDocument();
xmlDoc->LoadFileByCocos2d("test.xml",TIXML_ENCODING_UTF8);
TiXmlElement *xmlRoot = xmlDoc->RootElement();
TiXmlElement *xmlSet = xmlRoot->FirstChildElement();
while(xmlSet)
{
TiXmlAttribute *pAttribute = xmlSet->FirstAttribute();
while(pAttribute)
{
M_Map = pAttribute->Value();
pAttribute = pAttribute->Next();
}
xmlSet = xmlSet->NextSiblingElement();
}
delete xmlDoc;
}
OK! 搞定!
附件是TinyXML的代码~! 301
有问题请和我联系~ KuMo QQ: url ~
PS: win 和 android下都没有问题~ ios未测试 应该也可以~