void HelloWorld::writeXML(string path)
{
{
{
//获得文件路径
std::string filePath = FileUtils::getInstance()->getWritablePath() + path;
//获取XML操作对象
tinyxml2::XMLDocument *pDoc = new tinyxml2::XMLDocument();
//xml 声明(参数可选)
XMLDeclaration *pDel = pDoc->NewDeclaration("xml version=\"1.0\" encoding=\"UTF-8\"");
pDoc->LinkEndChild(pDel);
//添加plist节点
XMLElement *plistElement = pDoc->NewElement("plist");
plistElement->SetAttribute("version", "1.0");
pDoc->LinkEndChild(plistElement);
//添加注释
XMLComment *commentElement = pDoc->NewComment("this is xml comment");
plistElement->LinkEndChild(commentElement);
//添加dic节点
XMLElement *dicElement = pDoc->NewElement("dic");
plistElement->LinkEndChild(dicElement);
//添加key节点
XMLElement *keyElement = pDoc->NewElement("key");
//添加key节点text
keyElement->LinkEndChild(pDoc->NewText("Text"));
dicElement->LinkEndChild(keyElement);
XMLElement *arrayElement = pDoc->NewElement("array");
dicElement->LinkEndChild(arrayElement);
for (int i = 0; i<3; i++) {
XMLElement *elm = pDoc->NewElement("name");elm->LinkEndChild(pDoc->NewText("Cocos2d-x"));arrayElement->LinkEndChild(elm);
}delete pDoc;
//创建文件
pDoc->SaveFile(filePath.c_str());
//保存数据
pDoc->Print();
}
{
std::string filePath = FileUtils::getInstance()->getWritablePath() +path;
tinyxml2::XMLDocument *pDoc = new tinyxml2::XMLDocument();
log("path : %s",filePath.c_str());
XMLError errorId = pDoc->LoadFile(filePath.c_str());
if (errorId != 0) {
log("error : %d",errorId);
//xml格式错误
return;
}
XMLElement *rootEle = pDoc->RootElement();
//获取第一个节点属性
const XMLAttribute *attribute = rootEle->FirstAttribute();
//打印节点属性名和值
log("attribute_name = %s,attribute_value = %s", attribute->Name(), attribute->Value());
XMLElement *dicEle = rootEle->FirstChildElement("dic");
XMLElement *keyEle = dicEle->FirstChildElement("key");
if (keyEle) {
log("keyEle Text= %s", keyEle->GetText());
}
XMLElement *arrayEle = keyEle->NextSiblingElement();
XMLElement *childEle = arrayEle->FirstChildElement()
while ( childEle ) {
log("childEle Text= %s", childEle->GetText());childEle = childEle->NextSiblingElement();
}}
delete pDoc;