二 cocos2dx 之 解析xml文件数据并在程序中调用,存储

来源:互联网 发布:苗阜与姜昆的关系知乎 编辑:程序博客网 时间:2024/05/17 18:15

       微数据的读写,存储一般都习惯用json或者xml来存储,json不细说,我一般不大用,今天来说一说xml的解析方法以及运用方式:先上xml例子:

   <Plants plant_num="1" >    <plant  Name="芹菜"   Grow_rounds="1" shengji_jingyan="">        <Step Main_texture="" Min_texture="" feiliao_time="" yangguang="" shui=""  feiliao_cishu="" yangguang_cishu="" shui_cishu=         ""/>    </plant>   </Plants >
      在读取之前,我们要想好要以什么样的数据形式来读取,存储数据,这里给出我自己的例子,大家可以参考:

    

typedef struct step{    std::string Main_texture;    std::string Min_texture;    int feiliao_time;    int yangguang;    int shui;    int feiliao_cishu;    int yangguang_cishu;    int shui_cishu;}step;typedef struct zhiwu{    std::string Name;    int Grow_rounds;    int shengji_jingyan;    std::vector<step>arr_steps;}zhiwu;typedef struct plants{    int plant_num;    std::vector<zhiwu>arr_plants;}plants;
       根据xml的层次定义3个结构体分别对应xml的3个类型的节点。

        这个xml分3个级别:plants,plant和step,只要我们把它们的数据读取出来就可以了,上代码:

      

    ssize_t size;    const char *str="Plant/plant.xml";//xml的文件路径    const char *mode="r";    unsigned char *pFileContent =FileUtils::getInstance()->getFileData(str, mode, &size);    TiXmlDocument doc;    const char *p=(const char *)pFileContent;    doc.Parse(p, 0, TIXML_ENCODING_UTF8);    TiXmlElement* Plants = doc.FirstChildElement();//获取跟节点也就是plants    int plant_num=atoi(Plants->Attribute("plant_num"));    _zhiWuShuJu.plant_num=plant_num;    TiXmlElement *plant=Plants->FirstChildElement();//获取plants下的第一个节点    for(int i=0;i<plant_num;i++)//便利所有plant并解析数据    {        zhiwu z_w;        z_w.Name=plant->Attribute("Name");        z_w.Grow_rounds=atoi(plant->Attribute("Grow_rounds"));        z_w.shengji_jingyan=atoi(plant->Attribute("shengji_jingyan"));        TiXmlElement *ste=plant->FirstChildElement();        for(int i=0;i<z_w.Grow_rounds;i++)        {            step s_p;            s_p.Main_texture=ste->Attribute("Main_texture");            s_p.Min_texture=ste->Attribute("Min_texture");            s_p.feiliao_time=atoi(ste->Attribute("feiliao_time"));            s_p.yangguang=atoi(ste->Attribute("yangguang"));            s_p.shui=atoi(ste->Attribute("shui"));            s_p.feiliao_cishu=atoi(ste->Attribute("feiliao_cishu"));            s_p.yangguang_cishu=atoi(ste->Attribute("yangguang_cishu"));            s_p.shui_cishu=atoi(ste->Attribute("shui_cishu"));            ste=ste->NextSiblingElement();            z_w.arr_steps.push_back(s_p);        }        _zhiWuShuJu.arr_plants.push_back(z_w);        plant=plant->NextSiblingElement();    }
 本文用的tinyxml,自行百度下载封装好的类,导入自己的项目就可以用。


0 0