导入头文件:
#include "support/tinyxml2/tinyxml2.h"
一:创建XML并保存
//要储存XML文件的路径 std::string filePath = CCfileUtils::sharedfileUtils()->getWritablePath() + "woCiao.xml"; //xml文档 XMLdocument *pDoc = new XMLdocument(); if (NulL==pDoc) { return ; } //xml声明 XMLDeclaration *pDel = pDoc->NewDeclaration("xml version=\"1.0\" enCoding=\"UTF-8\""); if (NulL==pDel) { return ; } pDoc->linkEndChild(pDel); //节点pList XMLElement *pListElement = pDoc->NewElement("pList"); pListElement->SetAttribute("version","1.0");//给节点设置属性 pDoc->linkEndChild(pListElement); //节点dict XMLElement *dictElement = pDoc->NewElement("dict"); pListElement->linkEndChild(dictElement); //节点key XMLElement *keyElement = pDoc->NewElement("key"); keyElement->linkEndChild(pDoc->NewText("keyText"));//给节点设置值 dictElement->linkEndChild(keyElement); //节点string XMLElement *stringElement = pDoc->NewElement("string"); stringElement->linkEndChild(pDoc->NewText("stringText"));//给节点设置值 dictElement->linkEndChild(stringElement); //节点array XMLElement *arrayElemet = pDoc->NewElement("array"); dictElement->linkEndChild(arrayElemet); for (int i = 0; i<3; i++) { XMLElement *strEle = pDoc->NewElement("string"); strEle->linkEndChild(pDoc->NewText("icon")); arrayElemet->linkEndChild(strEle); } pDoc->Savefile(filePath.c_str());//保存文件 参数:路径 pDoc->Print();//打印 delete pDoc;输出:
<?xml version="1.0" enCoding="UTF-8"?><pList version="1.0"> <dict> <key>keyText</key> <string>stringText</string> <array> <string>icon</string> <string>icon</string> <string>icon</string> </array> </dict></pList>
二、解析
//xml文件路径 std::string filePath = CCfileUtils::sharedfileUtils()->getWritablePath() + "woCiao.xml";//xmlDoc XMLdocument *pDoc = new XMLdocument(); pDoc->Loadfile(filePath.c_str()); //得到跟节点 XMLElement *rootEle = pDoc->RootElement(); //打印节点的值 cclog("%s",rootEle->GetText()); //节点的第一个属性 const XMLAttribute *attribute = rootEle->FirstAttribute(); //打印属性的名字和值 cclog("%s %s",attribute->name(),attribute->Value()); //查找节点的属性值 float value = 0.1f; rootEle->queryfloatAttribute("version",&value); cclog("%f",value); //设置节点属性值 rootEle->SetAttribute("version",1.4); //跟节点的第一个字节点 dict XMLElement *dictEle = rootEle->FirstChildElement(); //dict下面的子节点 key XMLElement *keyEle = dictEle->FirstChildElement(); //打印key节点的值 cclog("%s,%s",keyEle->name(),keyEle->GetText()); //key节点的next节点 string XMLElement *stringEle = keyEle->NextSiblingElement(); cclog("%s,stringEle->name(),stringEle->GetText()); //string节点的子节点 XMLElement *nulXmlEle = stringEle->FirstChildElement(); if (NulL == nulXmlEle) { cclog("string下面没有子点了"); } //保存xml pDoc->Savefile(filePath.c_str());总结
以上是内存溢出为你收集整理的cocos2d-x使用tinyxml2解析&存储xml全部内容,希望文章能够帮你解决cocos2d-x使用tinyxml2解析&存储xml所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)