cocos2d-x基础(五)tinyXML2

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路径下















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值