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

       微数据的读写,存储一般都习惯用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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值