【Cocos2d-x 021】 xml解析

前端之家收集整理的这篇文章主要介绍了【Cocos2d-x 021】 xml解析前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

xml生成

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

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

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,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,att0->Name(),att0->Value());


原文链接:https://www.f2er.com/xml/297349.html

猜你在找的XML相关文章