展会信息港展会大全

Cocos2dx 3.0 提高篇(十一) xml文档的读取与调用
来源:互联网   发布日期:2015-09-26 18:09:30   浏览:1372次  

导读:这阶段很忙,灰常忙,人又感冒了。前两天去报了驾校,所以下班回家后都在突击科目一,争取下周就去考。话说我们这边驾校报名费要六千,全国还有其他地方有这么高的吗?-----------------...

这阶段很忙,灰常忙,人又感冒了。前两天去报了驾校,所以下班回家后都在突击科目一,争取下周就去考。话说我们这边驾校报名费要六千,全国还有其他地方有这么高的吗?

--------------------------------

前天有人问我beta2 要如何读取xml文档,我刚要说用array的相关接口去读取,才想起beta之后早没有array这玩意了。

那么既然之前是用arry读取,那么现在应该是可以用 容器 来读取吧?

最后我找到了这么两个函数接口:

ValueVector p_vec = FileUtils::getInstance()->getValueVectorFromFile("label.plist");

ValueMap p_map = FileUtils::getInstance()->getValueMapFromFile("label.xml");

那么,具体该怎么用呢。我之前有写过一篇博客,就是从xml文档读取中文的,

接下来就将那篇博客的代码移植到3.0 beta上。我用ValueVector的方法。

传送门:http://blog.csdn.net/start530/article/details/18740733

假设有一个名为 label.xml 的文档,内容如下:

id10info风一般的男纸id20info注定是寂寞的

步骤如下:

1、读取xml文档,将读取到的内容放到ValueVector上。

2、通过id获取info里的内容;

3、将info里的内容显示到label中。代码实现:1、读取

ValueVector txt_vec = FileUtils::getInstance()->getValueVectorFromFile("label.xml");

这里有两个要点,一个是ValueVector,这是啥东东?我只能回答在,在CCValue.h里,有这么一行代码 :

typedef std::vector ValueVector;

恩,人艰不拆;

第二个要点是用 getValueVectorFromFile(FileName)读取xml文档...

2、提取数据

首先提取 id ,因为id和它对应的值是一对键值,所以可以用Map来存储它们:

auto txt_map = txt_vec.at(0).asValueMap();

放到Map中即可用Map的方法读取键为”id"的值是多少:

int id_int = txt_map.at("id").asInt();

最后就是做出判断,如果id的值为10的话,那么提取相应的键为 info 的值:

if(id_int == 10)

{

auto label_str = txt_map.at("info").asString();

}

恩,过程就是这样;3、将整理好的代码贴出来

ValueVector txt_vec = FileUtils::getInstance()->getValueVectorFromFile("label.xml");//读取xml文档,放入ValueVector中

for( auto& e : txt_vec)

{

auto txt_map = e.asValueMap();//将键值转化成Map格式,放入txt_map中

int id_int = txt_map.at("id").asInt();//获取id

if(10 == id_int)

{

auto label_str = txt_map.at("info").asString();//获取info的值

auto label1 = LabelTTF::create(label_str,"Arial",25);

label1->setPosition(Point(160,425));

this->addChild(label1,2);

}

else if(20 == id_int)

{

auto label_str = txt_map.at("info").asString();

auto label1 = LabelTTF::create(label_str,"Arial",25);

label1->setPosition(Point(160,400));

this->addChild(label1,2);

}

}

如果有对Vector 、 Map使用不大了解的人,可以参考我之前写的博客:

Vector:http://blog.csdn.net/start530/article/details/19170853

Map:http://blog.csdn.net/start530/article/details/19284301

恩,就酱紫。

赞助本站

人工智能实验室

相关热词: Cocos2d 游戏开发 教程

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港