Cocos2dx 3.0 過渡篇(十一) xml文檔的讀取與調用
尊重原創,轉載請注明來自:star特530的CSDN博客 https://blog.csdn.net/start530/article/details/19632869
這階段很忙,灰常忙,人又感冒了。前兩天去報了駕校,所以下班回家後都在突擊科目一,爭取下周就去考。話說我們這邊駕校報名費要六千,全國還有其他地方有這麼高的嗎?
--------------------------------
前天有人問我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的方法。
傳送門:https://blog.csdn.net/start530/article/details/18740733
假設有一個名為 label.xml 的文檔,內容如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
- <plist version="1.0">
- <array>
- <dict>
- <key>id</key>
- <string>10</string>
- <key>info</key>
- <string>風一般的男紙</string>
- </dict>
- <dict>
- <key>id</key>
- <string>20</string>
- <key>info</key>
- <string>注定是寂寞的</string>
- </dict>
- </array>
- </plist>
步驟如下:
1、讀取xml文檔,將讀取到的內容放到ValueVector上。
2、通過id獲取info裏的內容;
3、將info裏的內容顯示到label中。
- ValueVector txt_vec = FileUtils::getInstance()->getValueVectorFromFile("label.xml");
這裏有兩個要點,一個是ValueVector,這是啥東東?我隻能回答在,在CCValue.h裏,有這麼一行代碼 :
- typedef std::vector<Value> 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:https://blog.csdn.net/start530/article/details/19170853
Map:https://blog.csdn.net/start530/article/details/19284301
恩,就醬紫。
最後更新:2017-04-03 12:56:12