如何在IOS上编写数据TINYXML2

how to write data TINYXML2 on IOS

本文关键字:数据 TINYXML2 IOS      更新时间:2023-10-16

我的test.xml像这样:

<?xml version="1.0"?>
<!DOCTYPE PLAY SYSTEM "play.dtd">            
<data>
    <CurrentLevel>5</CurrentLevel>
    <BestScoreLV1>1</BestScoreLV1>
    <BestScoreLV2>2</BestScoreLV2>
</data>
<dict/>

My Code here:

std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathFromRelativePath("text.xml");
tinyxml2::XMLDocument doc;
doc.LoadFile(fullPath.c_str());
tinyxml2::XMLElement* ele =  doc.FirstChildElement("data")->FirstChildElement("BestScoreLV2")->ToElement();
ele->SetAttribute("value", 10);
doc.SaveFile(fullPath.c_str());
const char* title1 =  doc.FirstChildElement("data")->FirstChildElement("BestScoreLV2")->GetText();
int level1  = atoi(title1);
CCLOG("result is: %d",level1);

但是输出时BestScoreLV2的值也是2。如何将数据更改和写入XML?

在TinyXML2中,文本由XMLText类表示,它是XMLNode类的子类。XMLNode的方法Value()SetValue()对不同的XML节点有不同的含义。对于文本节点,Value()读取节点文本,SetValue()写入节点文本。所以你需要这样的代码:

tinyxml2::XMLNode* value = doc.FirstChildElement("data")->
    FirstChildElement("BestScoreLV2")->FirstChild();
value->SetValue("10");

BestScoreLV2元素的第一个子元素是XMLText,值为2。您可以通过调用SetValue(10)将此值更改为10