ReadXML.h文件
#pragma once
#include "cocos2d.h"
USING_NS_CC;
class ReadXML
{
public:
ReadXML(void);
~ReadXML(void);
//---创建读取XML文件指针单例---//
static ReadXML* sharedXML();
//---初始化数据,fileXML为要读取的XML文件名字---//
bool initData(char* flieXML);
//---获取类型信息,name为要获取的标记 index为ID号组---//
int getIntData(char* name, int index);
float getFloatData(char* name, int index);
CCString* getStringData(char* name, int index);
/*CCAnimation* getAnimationData(char* name, int index);*/
private:
//---本来的唯一指针---//
static ReadXML* read;
//---保存XML中的数据---//
CCArray* DataGroup;
};
ReadXML.cpp文件
#include "ReadXML.h"
ReadXML* ReadXML::read = NULL;
ReadXML::ReadXML(void)
{
}
ReadXML::~ReadXML(void)
{
}
ReadXML* ReadXML::sharedXML()
{
if(!read)
read = new ReadXML();
return read;
}
bool ReadXML::initData(char* flieXML)
{
DataGroup = CCArray::create();
DataGroup->retain();
std::string path=CCFileUtils::sharedFileUtils()->fullPathForFilename(flieXML);
tinyxml2::XMLDocument *pXMLDoc=new tinyxml2::XMLDocument();
unsigned long nSize;
const char * pXMLBuffer=(const char *)CCFileUtils::sharedFileUtils()->getFileData(path.c_str(),"rb",&nSize);
if(!pXMLBuffer){
CCLog("is not xml data");
return false;
}
pXMLDoc->Parse(pXMLBuffer);
delete [] pXMLBuffer;
tinyxml2::XMLElement * pRootElem=pXMLDoc->RootElement();
tinyxml2::XMLElement * pCurChild=pRootElem->FirstChildElement();
while (pCurChild)
{
CCDictionary * pDict=CCDictionary::create();
tinyxml2::XMLElement * pCurTag=pCurChild->FirstChildElement();
while(pCurTag){
pDict->setObject(CCString::create(pCurTag->GetText()),pCurTag->Value());
pCurTag=pCurTag->NextSiblingElement();
}
DataGroup->addObject(pDict);
pCurChild=pCurChild->NextSiblingElement();
}
return true;
}
int ReadXML::getIntData(char* name, int index)
{
int data;
CCDictionary *pTempDic=(CCDictionary *)DataGroup->objectAtIndex(index);
sscanf(((CCString*)pTempDic->objectForKey(name))->getCString(),"%d",&data);
return data;
}
float ReadXML::getFloatData(char* name, int index)
{
float data;
CCDictionary *pTempDic=(CCDictionary *)DataGroup->objectAtIndex(index);
sscanf(((CCString*)pTempDic->objectForKey(name))->getCString(),"%f",&data);
return data;
}
CCString* ReadXML::getStringData(char* name, int index)
{
CCDictionary *pTempDic=(CCDictionary *)DataGroup->objectAtIndex(index);
return ((CCString*)pTempDic->objectForKey("filename"));
}