Cocos2d-x 已经加入了tinyxml2
用于xml的解析。3.0版本位于external/tinyxml2
下。2.x版本位于cocos2dx/support/tinyxml2
下
生成xml文档
-
引入头文件
#include "tinyxml2/tinyxml2.h" using namespace tinyxml2;
-
xml文档生成
void HelloWorld::makeXML(constchar *fileName) { std::string filePath = FileUtilsgetInstance()->getWritablePath()+ fileName; XMLDocumentpDoc newXMLDocument(); //xml 声明(参数可选)XMLDeclarationpDel pDoc->NewDeclaration("xml version=\"1.0\" encoding=\"UTF-8\""); pDocLinkEndChild(pDel//添加plist节点XMLElementplistElement NewElement"plist" plistElementSetAttribute"version","1.0"plistElementXMLCommentcommentElement NewComment"this is xml comment"commentElement//添加dic节点dicElement "dic"dicElement//添加key节点keyElement "key" keyElementpDocNewText"Text")); dicElementkeyElementarrayElement "array"arrayElementforint i 0 i<3++) elm "name" elm"Cocos2d-x" arrayElementelm}SaveFilefilePath.c_str());Printdelete}
-
打印结果
<?xml version="1.0" encoding"UTF-8"?> <plist version="1.0"><!--this is xml comment--><dic> <key>Text</key><array> <name>Cocos2d-x</name></array></dic></plist>
解析xml
下面我们就来解析上面创建的xml文档
- ;
-
xml解析
parseXMLXMLError errorId LoadFileiferrorId != //xml格式错误 returnrootEle RootElement//获取第一个节点属性XMLAttributeattribute rootEleFirstAttribute//打印节点属性名和值 log"attribute<em>name = %s,attribute</em>value = %s" attributeName(),102)">Value());</p>dicEle FirstChildElementkeyEle dicElekeyEle log"keyEle Text= %s" keyEleGetTextarrayEle NextSiblingElementchildEle arrayElewhile childEle "childEle Text= %s" childEle childEle }
在节点解析过程中,注意对获取到的节点进行判空处理。
-
解析结果打印
cocos2d: attribute_name versionattribute_value 1.0 cocos2d keyEle TextText childEle Cocos2d-x cocos2dx
上面的简单示例,演示了如何使用tinyxml进行xml文档生成和解析。更多详细的帮助请参考 tinyxml帮助文档http://grinninglizard.com/tinyxml2docs/index.html
源地址:http://www.tairan.com/archives/7340