【Cocos2d-x 021】 xml解析

来源:互联网 发布:中国手工艺品出口数据 编辑:程序博客网 时间:2024/04/28 00:47

xml生成

我们现在生成一个create.xml
<language name="CH">
<!-- this is a xml file! -->
<tip ch="tiptiptip" en="a tip">Text</tip>
</language>

1、引入头文件
#include "support/tinyxml2/tinyxml2.h"
using namespace tinyxml2;

2、生成代码
tinyxml2::XMLDocument * doc=new tinyxml2::XMLDocument();
//声明
/*tinyxml2::XMLDeclaration * dec=doc->NewDeclaration("<?xml version='1.0' encoding='UTF-8' ?>");
doc->LinkEndChild(dec);*/

//添加根节点及属性
tinyxml2::XMLElement * eleRoot=doc->NewElement("language");
eleRoot->SetAttribute("name","CH");
doc->LinkEndChild(eleRoot);
//注释
tinyxml2::XMLComment * com=doc->NewComment("this is a xml file!");
eleRoot->LinkEndChild(com);

//添加子节点及属性
tinyxml2::XMLElement * ele0=doc->NewElement("tip");
ele0->SetAttribute("ch","tiptiptip");
ele0->SetAttribute("en","a tip");
ele0->LinkEndChild(doc->NewText("Text"));
eleRoot->LinkEndChild(ele0);

string path=CCFileUtils::sharedFileUtils()->getWritablePath()+"create.xml";
doc->SaveFile(path.c_str());
delete doc;





xml解析
tinyxml2::XMLDocument * doc=new tinyxml2::XMLDocument();
string path=CCFileUtils::sharedFileUtils()->getWritablePath()+"create.xml";
tinyxml2::XMLError error=doc->LoadFile(path.c_str());
if(error!=tinyxml2::XML_SUCCESS){
return "No corresponding data found";;
}

//根元素
tinyxml2::XMLElement * eleRoot=doc->RootElement();
CCLog("create.xml eleRoot>> name=%s, value=%s",eleRoot->Name(),eleRoot->Value());
//根元素的属性
const tinyxml2::XMLAttribute * attRoot=eleRoot->FirstAttribute();
CCLog("create.xml attRoot>> name=%s, value=%s",attRoot->Name(),attRoot->Value());

//根元素的子元素
tinyxml2::XMLElement * ele0=eleRoot->FirstChildElement();
CCLog("create.xml ele0>> name=%s, value=%s, content=%s",ele0->Name(),ele0->Value(),ele0->FirstChild()->Value());
//子元素属性
const tinyxml2::XMLAttribute * att0=ele0->FirstAttribute();
CCLog("create.xml att0>> name=%s, value=%s",att0->Name(),att0->Value());



0 0
原创粉丝点击