cocos2dx讀寫xml檔案
首先包含標頭檔案
#include "tinyxml2/tinyxml2.h"
usingnamespace tinyxml2;
//data.xml檔案內容
<Chapters>
<Chapter>
<Name>Misty Vale</Name>
<Number>1</Number>
<Unlocked>1</Unlocked>
</Chapter>
<Chapter>
<Name>Bamboo Vale</Name>
<Number>2</Number>
<Unlocked>0</Unlocked>
</Chapter>
<Chapter>
<Name>Wind Vale</Name>
<Number>3</Number>
<Unlocked>0</Unlocked>
</Chapter>
<Chapter>
<Name>Kunlun Mountain</Name>
<Number>4</Number>
<Unlocked>0</Unlocked>
</Chapter>
<Chapter>
<Name>Happy Vale</Name>
<Number>5</Number>
<Unlocked>0</Unlocked>
</Chapter>
</Chapters>
具體程式碼:
FileUtils* f = FileUtils::getInstance();
//獲得可寫的具體檔案路徑
std::string path = f -> getWritablePath();
std::string xmlPath = path + std::string("data.xml");
log("%s",xmlPath.c_str());
XMLDocument* myDocument = new XMLDocument();
XMLError errorID = myDocument -> LoadFile(xmlPath.c_str());
//判斷是否解析錯誤
if (errorID != 0) {
log("Parse Error!");
delete myDocument;
return;
}
//獲取根節點
XMLElement* RootElement=myDocument->RootElement();
CCLOG("RoorKey=%s",RootElement->Value());//獲取建
log("RootValue=%s",RootElement->GetText());//獲取值
XMLElement *chapterElement = RootElement->FirstChildElement();//RootElement下的第一個
log("1chapterElement=%s",chapterElement->Value());
log("1chapterElement=%s",chapterElement->GetText());//獲取值
XMLElement *element = chapterElement->NextSiblingElement();//chapterElement->NextSiblingElement()如果取不到節點了,則為空,可以搭配while語句遍歷所有節點
log("2chapterElement=%s",element->Value());//RootElement下的第二個
log("2chapterElement=%s",element->GetText());
XMLElement *nameElement = element->FirstChildElement();//element下的第一個
log("nameElement:%s",nameElement->Value());
log("nameElementValue:%s",nameElement->GetText());
XMLElement *numElement = nameElement->NextSiblingElement();//element下的第二個,即nameElement的下一個
log("num%s",numElement->Value());//獲取鍵
log("numValue%s",numElement->GetText());//這裡獲取值
//修改節點
XMLNode *oldNode = numElement->FirstChild();//注意分析FirstChild和FirstChildElement的區別
log("oldNodeValue:%s",oldNode->Value());
oldNode->SetValue("xiugaileeeeee"); //注意這裡要用父類的節點呼叫,否則會不起作用
myDocument->SaveFile(xmlPath.c_str());//這個將修改儲存到檔案
//新增節點,需要使用父類節點呼叫,若使用同等級的子節點,則會作為起子節點新增
XMLElement* Broadcast_Pid = myDocument->NewElement("AGE");//<AGE></AGE>
XMLText *text1 =myDocument->NewText("3333");
Broadcast_Pid->SetAttribute("info","the pid");
Broadcast_Pid->LinkEndChild(text1);//<AGE info=the pid>3333</AGE>
chapterElement->LinkEndChild(Broadcast_Pid);//最後把這個節點又加上了
myDocument->SaveFile(xmlPath.c_str());
//移除節點
XMLElement* nameNode=chapterElement->FirstChildElement();
chapterElement->DeleteChild(nameNode);
myDocument->SaveFile(xmlPath.c_str());
delete myDocument;