现在的位置: 首页 > 综合 > 正文

cocos2d-x基础(五)tinyXML2

2017年09月16日 ⁄ 综合 ⁄ 共 2495字 ⁄ 字号 评论关闭

1、首先添加tinyXML2的库:#include "support/tinyxml2/tinyxml2.h"

2、引入命名空间:using namespace tinyxml2;但是不知道为什么引入后还是需要在定义相关的

对象前加入tinyxml2::

3、写入XML文件

      //要储存XML文件的路径(XML将会存储在proj.win32\Debug.win32下,还有另外一种方法:

      //CCFileUtils::sharedFileUtils()->fullPathForFilename("HighScore.xml").c_str())

   //将会存储在Resources下

CCString filePath=CCFileUtils::sharedFileUtils()->getWritablePath()+"HighScore.xml";
CCLog("%s",filePath.getCString());

//xml文档
tinyxml2::XMLDocument *pDoc=new tinyxml2::XMLDocument();
//xml声明
tinyxml2::XMLDeclaration *pDel=pDoc->NewDeclaration("xml version=\"1.0\" encoding=\"UTF-8\"");
//将声明链接到文档中
pDoc->LinkEndChild(pDel);

//节点plist
tinyxml2::XMLElement *plistElement=pDoc->NewElement("plist");
plistElement->SetAttribute("version","1.0");//给节点设置属性、
pDoc->LinkEndChild(plistElement);

//节点dict
tinyxml2::XMLElement *dictElement=pDoc->NewElement("dict");
plistElement->LinkEndChild(dictElement);

//节点key
tinyxml2::XMLElement *keyElement=pDoc->NewElement("key");
keyElement->LinkEndChild(pDoc->NewText("keyText"));//给节点设置值
dictElement->LinkEndChild(keyElement);

//节点Array
tinyxml2::XMLElement *arrayElement=pDoc->NewElement("array");
dictElement->LinkEndChild(arrayElement);
for (int i=0;i<3;i++)
{
tinyxml2::XMLElement *strEle = pDoc->NewElement("string");
strEle->LinkEndChild(pDoc->NewText("icon"));
arrayElement->LinkEndChild(strEle);
}

//保存文件
pDoc->SaveFile(filePath.getCString());

delete pDoc;

4、读取XML文件

//xml文件路径
CCString filePath=CCFileUtils::sharedFileUtils()->getWritablePath()+"HighScore.xml";

//XMLdoc
tinyxml2::XMLDocument *pDoc=new tinyxml2::XMLDocument();

//载入XML文件        

  pDoc->LoadFile(filePath.getCString());

       //得到根节点
tinyxml2::XMLElement *rootEle=pDoc->RootElement();
CCLog("%s",rootEle->GetText());

//节点的第一个属性
const tinyxml2::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
tinyxml2::XMLElement *dictEle=rootEle->FirstChildElement();
//dict下面的子节点key
tinyxml2::XMLElement *keyEle=dictEle->FirstChildElement();
//打印key节点的值
CCLog("%s %s",keyEle->Name(),keyEle->GetText());
//key节点的next节点string
tinyxml2::XMLElement *stringEle=keyEle->NextSiblingElement();
CCLog("%s %s",stringEle->Name(),stringEle->GetText());

//string节点的子节点
tinyxml2::XMLElement *nulXMLEle=stringEle->FirstChildElement();
if (NULL==nulXMLEle)
{
CCLog("string下面没有子节点");
}

//保存xml
pDoc->SaveFile(filePath.getCString());

//关于保存的第二个方法

pDoc->SaveFile(“"HighScore.xml"”);它会直接保存到Resources路径下

抱歉!评论已关闭.