xml解析类如下:
//
// HXmlParse.h
// ParseXmlTest
//
// Created by Himi on 12-10-14.
//
//
#ifndef __ParseXmlTest__HXmlParse__
#define __ParseXmlTest__HXmlParse__
#include "cocos2d.h"
#include "CCSAXParser.h"
#include "CCObject.h"
using namespace cocos2d;
using namespace std;
class CC_DLL HXmlParse :public CCObject, public CCSAXDelegator
{
public:
static HXmlParse * parserWithFile(const char *tmxFile);
bool initHXmlParse(const char* xmlName);
string root_name;
bool isJumpHeadData;
~HXmlParse();
vector< string> allData;//用于记录所有数据
// 使用 CCSAXDelegator 重写3个回调函数
//开始解析时回调
void startElement(void *ctx, const char *name, const char **atts);
//结束解析回调
void endElement(void *ctx, const char *name);
//键值对的结束字段
void textHandler(void *ctx, const char *ch, int len);
private:
string startXmlElement;//用来记录每个key前字段
string endXmlElement;//用来记录每个key后字段
string currString;//记录每个value的值
};
#endif /* defined(__ParseXmlTest__HXmlParse__) */
//
// HXmlParse.cpp
// ParseXmlTest
//
// Created by Himi on 12-10-14.
//
//
#include "HXmlParse.h"
#include "CCSAXParser.h"
HXmlParse * HXmlParse::parserWithFile(const char *tmxFile)
{
HXmlParse *pRet = new HXmlParse();
if(pRet->initHXmlParse(tmxFile))
{
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
bool HXmlParse::initHXmlParse(const char* xmlName)
{
CCSAXParser _par;
if (false == _par.init("UTF-8") )
{
CCLog("请使用utf-8格式!");
return false;
}
_par.setDelegator(this);
//获取文件的完整相对路径
const char* _path =CCFileUtils::sharedFileUtils()->fullPathFromRelativePath(xmlName);
return _par.parse(_path);
}
//开始解析时回调
void HXmlParse::startElement(void *ctx, const char *name, const char **atts)
{
CC_UNUSED_PARAM(ctx);
startXmlElement = (char*)name;
if(!isJumpHeadData){//跳过数据头
CCLog("------跳过root name");
isJumpHeadData=true;
root_name=startXmlElement;
return;
}
}
//结束解析回调
void HXmlParse::endElement(void *ctx, const char *name)
{
CC_UNUSED_PARAM(ctx);
endXmlElement = (char*)name;
if(endXmlElement==root_name){//数据尾
CCLog("读取xml结束");
isJumpHeadData=false;
root_name="";
return;
}
}
//键值对的结束字段
void HXmlParse::textHandler(void *ctx, const char *ch, int len)
{
CC_UNUSED_PARAM(ctx);
currString=string((char*)ch,0,len);
if(root_name!=""){
allData.push_back(currString);
}
}
//析构函数释放内存
HXmlParse::~HXmlParse()
{
for (int i=0; i<allData.size(); i++) {
allData[i].clear();
}
allData.clear();
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !CCLayer::init() )
{
return false;
}
CCLabelTTF *pLabel=CCLabelTTF::create("xml 文件中读取的数据如下:", "Thonburi", 28);
CCSize size=CCDirector::sharedDirector()->getWinSize();
pLabel->setPosition(ccp(size.width/2,size.height-20));
this->addChild(pLabel,1);
HXmlParse* parseXml=HXmlParse::parserWithFile("test.xml");//xml文件
for (int i=0; i
CCLabelTTF *pLabel=CCLabelTTF::create(parseXml->allData[i].c_str(), "Thonburi", 20);
pLabel->setPosition(ccp(size.width/2,size.height-70-(30*i)));
this->addChild(pLabel,1);
}
return true;
}