Cocos2d-3.x_读取xml文件

前端之家收集整理的这篇文章主要介绍了Cocos2d-3.x_读取xml文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

测试的data.xml文件内容如下:

  1. <data>
  2. <p name="cxm" age="20"/>
  3. <p name="zqr" age="30"/>
  4. <p name="zrk" age="40"/>
  5. </data>
  1. #ifndef __HELLOWORLD_SCENE_H__
  2. #define __HELLOWORLD_SCENE_H__
  3.  
  4. #include "cocos2d.h"
  5.  
  6. USING_NS_CC;
  7.  
  8.  
  9. class HelloWorld : public cocos2d::Layer
  10. {
  11. public:
  12. static cocos2d::Scene* createScene();
  13.  
  14. virtual bool init();
  15.  
  16. void readXmlByCocosAPI();
  17.  
  18. CREATE_FUNC(HelloWorld);
  19.  
  20. private:
  21. LabelTTF *pLabel;
  22. };
  23.  
  24. #endif // __HELLOWORLD_SCENE_H__
  1. #include "HelloWorldScene.h"
  2. #include "tinyxml2/tinyxml2.h"
  3.  
  4. Scene* HelloWorld::createScene()
  5. {
  6. auto scene = Scene::create();
  7. auto layer = HelloWorld::create();
  8. scene->addChild(layer);
  9.  
  10. return scene;
  11. }
  12.  
  13. bool HelloWorld::init()
  14. {
  15. if ( !Layer::init() )
  16. {
  17. return false;
  18. }
  19. Size visibleSize = Director::getInstance()->getVisibleSize();
  20. Vec2 origin = Director::getInstance()->getVisibleOrigin();
  21.  
  22. pLabel = LabelTTF::create("","Arial",30);
  23. pLabel->setPosition(visibleSize/2.0);
  24. this->addChild(pLabel);
  25.  
  26. this->readXmlByCocosAPI();
  27.  
  28. return true;
  29. }
  30.  
  31. void HelloWorld::readXmlByCocosAPI()
  32. {
  33. auto doc = new tinyxml2::XMLDocument();
  34. doc->Parse(FileUtils::getInstance()->getStringFromFile("data.xml").c_str());
  35. auto root = doc->RootElement();
  36.  
  37. for (auto e = root->FirstChildElement(); e; e = e->NextSiblingElement())
  38. {
  39. std::string str;
  40. for (auto attr = e->FirstAttribute(); attr; attr = attr->Next())
  41. {
  42. str += attr->Name();
  43. str += ":";
  44. str += attr->Value();
  45. str += ",";
  46. }
  47. log("%s",str.c_str());
  48. }
  49.  
  50. CC_SAFE_DELETE(doc);
  51. }

猜你在找的Cocos2d-x相关文章