C++解析xml--tinyxml--DOM模型

还是使用了DOM模型...不习惯SAX






#include "ImageManager.h"
bool  ImageManager::init(){
	return loadTexture();
}
bool ImageManager::loadTexture(){
	std::string filePath = RESOURCES_PATH;
	tinyxml2::XMLDocument *pDoc = new tinyxml2::XMLDocument();
	XMLError errorId = pDoc->LoadFile(filePath.c_str());

	if (errorId != 0) {
		//xml格式错误
		return false;
	}
	XMLElement *rootEle = pDoc->RootElement();
	XMLElement *textEle = rootEle->FirstChildElement();
	while (textEle){
		std::string textpath=textEle->Attribute("filepath");
		auto textureAtlas = Director::getInstance()->getTextureCache()->addImage(textpath);
		loadPhoto(textureAtlas, textEle->FirstChildElement());
		textEle = textEle->NextSiblingElement();
	}
	delete pDoc;
}
bool ImageManager::loadPhoto(Texture2D *texture, XMLElement *ele){
	std::string resname;
	std::string range;
	int x, y, height, width;
	while (ele){
		resname = ele->Attribute("resname");
		char const *range=ele->Attribute("range");	
		sscanf(range, "%d,%d,%d,%d", &x, &y, &width, &height);
		Rect rect = Rect(x, y, width, height);
		auto frame = SpriteFrame::createWithTexture(texture, rect);
		frameMap.insert(resname, frame);
		ele = ele->NextSiblingElement();
	}
	return true;
}
SpriteFrame * ImageManager::getSpriteFrame(std::string name){
	return frameMap.at(name);
}
 Map<std::string, SpriteFrame *>ImageManager::frameMap;











<resources >
	<texture filepath="HelloWorld.png" resname="helloworld">
		<photo texturename="helloworld" resname="first" range="100,100,100,100"/>
		<photo texturename="helloworld" resname="second" range="200,200,50,50"/>
	</texture>
	<texture filepath="background.png" resname="background">
		<photo texturename="background" resname="backday" range="0,0,175,312"/>
		<photo texturename="background" resname="backnight" range="178,0,175,312"/>
	</texture>
	<texture filepath="bottom.png" resname="bottom">
		<photo texturename="bottom" resname="bottom" range="0,0,206,66"/>
	</texture>
	<texture filepath="yellowbird.png" resname="yellowbird">
		<photo texturename="yellowbird" resname="yellowbird1" range="0,0,40,29"/>
		<photo texturename="yellowbird" resname="yellowbird2" range="55,0,40,29"/>
		<photo texturename="yellowbird" resname="yellowbird3" range="110,0,40,29"/>
	</texture>
	<texture filepath="pipe.png" resname="pipe">
		<photo texturename="pipe" resname="redpipeup" range="0,0,53,325"/>
		<photo texturename="pipe" resname="redpipedown" range="54,0,53,325"/>
		<photo texturename="pipe" resname="greenpipeup" range="111,0,53,328"/>
		<photo texturename="pipe" resname="greenpipedown" range="164,0,53,29"/>
	</texture>
</resources>


你可能感兴趣的:(xml,dom)