引入头文件
<span style="font-size:18px;">#include "HelloWorldScene.h" #include "tinyxml2/tinyxml2.h" USING_NS_CC; using namespace tinyxml2;</span>
生成xml
<span style="font-size:18px;">void HelloWorld::makeXml(const char* fileName) { //写入路径 std::string filePath = FileUtils::getInstance()->getWritablePath() + fileName; XMLDocument *pDoc = new XMLDocument(); //头声明 XMLDeclaration *pDecl = pDoc->NewDeclaration("xml=version=\"1.0\" encoding=\"UTF-8\""); pDoc->LinkEndChild(pDecl); //注释 XMLComment *pCom = pDoc->NewComment("test xml"); pDoc->LinkEndChild(pCom); XMLElement *plistEl = pDoc->NewElement("plist"); plistEl->SetAttribute("version","1.0"); plistEl->SetAttribute("age",10); pDoc->LinkEndChild(plistEl); XMLElement *dictEl = pDoc->NewElement("dict"); plistEl->LinkEndChild(dictEl); XMLElement *keyEl = pDoc->NewElement("key"); keyEl->LinkEndChild(pDoc->NewText("keyValue")); dictEl->LinkEndChild(keyEl); XMLElement *arrayEl = pDoc->NewElement("array"); dictEl->LinkEndChild(arrayEl); for (int i = 0; i<2 ; i++) { XMLElement *nameEl = pDoc->NewElement("name"); nameEl->LinkEndChild(pDoc->NewText("array value")); arrayEl->LinkEndChild(nameEl); } pDoc->SaveFile(filePath.c_str()); pDoc->Print(); delete pDoc; }</span>
运行结果为:
<span style="font-size:18px;"><?xml=version="1.0" encoding="UTF-8"?> <!--test xml--> <plist version="1.0" age="10"> <dict> <key>keyValue</key> <array> <name>array value</name> <name>array value</name> </array> </dict> </plist></span>
读取xml:
void HelloWorld::parseXml(const char* fileName) { std::string filePath = FileUtils::getInstance()->getWritablePath() + fileName; XMLDocument *pDoc = new XMLDocument(); XMLError errorID = pDoc->LoadFile(filePath.c_str()); if (errorID != 0) { return; } XMLElement *rootEl = pDoc->RootElement(); const XMLAttribute *attribute = rootEl->FirstAttribute(); while (attribute) { CCLOG("name=%s,value = %s",attribute->Name(),attribute->Value()); attribute = attribute->Next(); } XMLElement *dictEl = rootEl->FirstChildElement("dict"); XMLElement *keyEl = dictEl->FirstChildElement("key"); if (keyEl) { CCLOG("key el is = %s",keyEl->GetText()); } XMLElement *arrayEl = keyEl->NextSiblingElement(); XMLElement *childEl = arrayEl->FirstChildElement(); while (childEl) { CCLOG("child el is = %s",childEl->GetText()); childEl = childEl->NextSiblingElement(); } }
结果为:
cocos2d: name=version,value = 1.0 cocos2d: name=age,value = 10 cocos2d: key el is = keyValue cocos2d: child el is = array value cocos2d: child el is = array value
tinyxml2官网地址在: http://grinninglizard.com/tinyxml2docs/index.html