#include"tinyxml2/tinyxml2.h"
usingnamespacetinyxml2;
<Chapters>
<Chapter>
<Name>Misty Vale</Name>
<Number>1</Number>
<Unlocked>1</Unlocked>
</Chapter>
<Name>Bamboo Vale</Name>
<Number>2</Number>
<Unlocked>0</Unlocked>
<Name>Wind Vale</Name>
<Number>3</Number>
<Name>Kunlun Mountain</Name>
<Number>4</Number>
<Name>Happy Vale</Name>
<Number>5</Number>
</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());
获取值
XMLElement *element = chapterElement->NextSiblingElement();//chapterElement->NextSiblingElement()如果取不到节点了,则为空,可以搭配while语句遍历所有节点
log("2chapterElement=%s",element->Value());//RootElement下的第二个
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);
delete myDocument;