第一步:
先要在TinyXml增加函数 bool TiXmlDocument::LoadMemory( const char * pBuff, int length, TiXmlEncoding encoding )
/// Load Xml form memory buff. Returns true if successful. bool TiXmlDocument::LoadMemory( const char * pBuff, int length, TiXmlEncoding encoding ) { if ( !pBuff || length == 0 ) { SetError( TIXML_ERROR, 0, 0, TIXML_ENCODING_UNKNOWN ); return false; } // If we have a file, assume it is all one big XML file, and read it in. // The document parser may decide the document ends sooner than the entire file, however. TIXML_STRING data; data.reserve( length ); char* buf = new char[ length+1 ]; buf[0] = 0; memcpy( buf, pBuff, length ); const char* lastPos = buf ; const char* p = buf ; buf[length] = 0; while( *p ) { assert( p < (buf+length) ); if ( *p == 0xa ) { // Newline character. No special rules for this. Append all the characters // since the last string, and include the newline. data.append( lastPos, (p-lastPos+1) ); // append, include the newline ++p; // move past the newline lastPos = p; // and point to the new buffer (may be 0) assert( p <= (buf+length) ); } else if ( *p == 0xd ) { // Carriage return. Append what we have so far, then // handle moving forward in the buffer. if ( (p-lastPos) > 0 ) { data.append( lastPos, p-lastPos ); // do not add the CR } data += (char)0xa; // a proper newline if ( *(p+1) == 0xa ) { // Carriage return - new line sequence p += 2; lastPos = p; assert( p <= (buf+length) ); } else { // it was followed by something else...that is presumably characters again. ++p; lastPos = p; assert( p <= (buf+length) ); } } else { ++p; } } // Handle any left over characters. if ( p-lastPos ) { data.append( lastPos, p-lastPos ); } delete [] buf; buf = 0; Parse( data.c_str(), 0, encoding ); if ( Error() ) { return false; } return true; }
第二步骤 调用
void readXml() { string documentPath = "heroList.xml"; TiXmlDocument *myDocument = new TiXmlDocument(documentPath.c_str());//"WriteTest.xml"); if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS) { /*因为android无法读取assets下的xml数据文件,ios同样存在读取问题,这个具体原因是因为apk和app实质上是一个压缩包, 压缩包的内容读取不同于一般的文件读取,因为文件已经被压缩过了, 所以采用了读取buffer的方法,通过将buffer交给LoadMemory解析,初始化TiXmlDocument *myDocument 中的数据。 */ unsigned long nLength = 0; char* pBuff = (char*)cocos2d::CCFileUtils::sharedFileUtils()->getFileData(CCFileUtils::sharedFileUtils()->fullPathForFilename(documentPath.c_str()).c_str(),"rt", &nLength ); myDocument->LoadMemory( pBuff, nLength); } else { myDocument->LoadFile(); } TiXmlElement *RootElement = myDocument->RootElement();/*读取根节点*/ if(RootElement == NULL) { //LD("read from data xml error!"); } TiXmlElement *FirstPerson = RootElement->FirstChildElement();/*读取根节点中的第一个节点数据*/ while (FirstPerson) { CCLog("node name = %s",FirstPerson->Value()); TiXmlAttribute *idAttribute = FirstPerson->FirstAttribute();/*我的文件中有两个属性值,一个是id属性*/ TiXmlAttribute *decAttribute = idAttribute->Next();/*我的文件中有两个属性值,一个是描述属性*/ CCLog("attrName = %s,attrValue = %d",idAttribute->Name(),atoi(idAttribute->Value()));/*打印出属性名称和属性值*/ CCLog("attrName = %s,attrValue = %s",decAttribute->Name(),decAttribute->Value()); TiXmlElement *firstChild = FirstPerson->FirstChildElement();/*读取第一个节点的第一个子节点*/ map<string,int> tempMap; while(firstChild) { /*读取第一个节点的数据*/ CCLog("childName = %s,childValue = %d",firstChild->Value(),atoi(firstChild->GetText())); tempMap.insert(map<string, int>::value_type (firstChild->Value(), atoi(firstChild->GetText()))); firstChild = firstChild->NextSiblingElement();/*读取完第一个节点的数据,firstChild指针向后移位,读取下一个节点的数据*/ string childName = string(firstChild->Value()); if ( childName == "boundRidus") { break; } } while(firstChild) { /*我自定义的"heroList.xml"中,本子节点有三个属性,依次读取三个属性,详细的数据已经注释在代码中了*/ TiXmlAttribute *posXAttribute = firstChild->FirstAttribute(); TiXmlAttribute *posYAttribute = posXAttribute->Next(); TiXmlAttribute *radiusAttr = posYAttribute->Next(); CCLog("attriName = %s,attriValue = %d",posXAttribute->Name(),atoi(posXAttribute->Value())); firstChild = firstChild->NextSiblingElement(); } //m_heroDatas.push_back(hData); FirstPerson = FirstPerson->NextSiblingElement(); } writeLevel(1); writeXml(); } void writeLevel(int level) { /*生成xml文件,这个尽量不要在正式的程序中使用,生成的xml数据只是为了方便配置数据的人员方便配置*/ const char * attribut[12] = {"mId","aId","pId","pAId","posX","posY","mType","explodeEffect","data8","data9","data10","data11"}; TiXmlDocument doc ; TiXmlDeclaration *declare =new TiXmlDeclaration("1.0" , "",""); doc.LinkEndChild(declare); doc.LinkEndChild(new TiXmlComment("levelDataInf")); TiXmlElement *root = new TiXmlElement("levelDataConfig"); for (int i=0;i!=4;++i) { TiXmlElement *sub = new TiXmlElement("createMonsters"); sub->SetAttribute("order" , i); // 向sub中添加属性 for(int enemyC=0;enemyC!=7;++enemyC) { TiXmlElement *monster = new TiXmlElement("monster"); for (int j=0;j!=12;++j) { monster->SetAttribute(attribut[j] , j); } // 向sub中添加属性 sub->LinkEndChild(monster); // 将child追加到sub中,以作为子元素 } root->LinkEndChild(sub); // 将sub } doc.LinkEndChild(root); string documentPath = "levelTest.xml"; doc.SaveFile(documentPath.c_str()); } void writeXml() { /*写文件,如果程序中使用了xml的进行读写数据,可以使用这个来重新写入游戏配置数据,不过本人尽量推荐使用CCUserDefault来做*/ TiXmlDocument doc ; TiXmlDeclaration *declare =new TiXmlDeclaration("1.0" , "",""); doc.LinkEndChild(declare); doc.LinkEndChild(new TiXmlComment("personalInfo")); TiXmlElement *personalInfo = new TiXmlElement("personalInfo"); doc.LinkEndChild(personalInfo); personalInfo->SetAttribute("userId", 0); personalInfo->SetAttribute("loginTime", 0); personalInfo->SetAttribute("url", 0); personalInfo->SetAttribute("scoreRecord", 0); personalInfo->SetAttribute("coinTotal", 0); personalInfo->SetAttribute("diamondTotal", 0); personalInfo->SetAttribute("character", 0); personalInfo->SetAttribute("knife",0); personalInfo->SetAttribute("sprint", 0); personalInfo->SetAttribute("protectCover", 9); personalInfo->SetAttribute("currentLevel",9); string documentPath = CCFileUtils::sharedFileUtils()->getWritablePath()+"writeData.xml"; /*此路径win 在../proj.win32/Debug.win32,android在/data/data/包名/,如果是ios在*/ doc.SaveFile(documentPath.c_str()); } 下面介绍TinyXML的一些类。在TinyXML中,根据XML的各种元素来定义了一些类: TiXmlBase:整个TinyXML模型的基类。 TiXmlAttribute:对应于XML中的元素的属性。 TiXmlNode:对应于DOM结构中的节点。 TiXmlComment:对应于XML中的注释 TiXmlDeclaration:对应于XML中的申明部分,<?versiong="1.0" ?>。 TiXmlDocument:对应于XML的整个文档。 TiXmlElement:对应于XML的元素。 TiXmlText:对应于XML的文字部分 TiXmlUnknown:对应于XML的未知部分。 TiXmlHandler:定义了针对XML的一些操作。