Exemplo n.º 1
0
int main()
{
	Document document("1.0");
	Element* root = new Element("map", "schmap");
	document.Set_root(root);

	Element* platform = new Element("platform", "boom");
	root->Add_child(platform);

	Element* x = new Element("x", "10");
	platform->Add_child(x);
	x->Set_attribute("foo", "baha");
	x->Set_attribute("att", "23");
	std::cout<<x->Get_attribute("att")<<std::endl;
	
	document.Save_file("test.xml");
	
	document.Load_file("test.xml");
	document.Save_file("test_copy.xml");
	
	Element* parent = document.Get_root();
	Children& children = parent->Get_children();
	for(Children::iterator i = children.begin(); i != children.end(); ++i)
	{
		std::cout<<(*i)->Get_name()<<" = "<<(*i)->Get_value()<<std::endl;
		std::cout<<(*i)->Get_child("x")->Get_value()<<std::endl;
		std::cout<<(*i)->Get_child("x")->Get_attribute("att")<<std::endl;
	}
	parent->Get_child("x");
	
	return 0;
}
Exemplo n.º 2
0
bool Document::Load_file(const std::string& filename)
{
	if(root)
	{
		delete root;
		root = NULL;
	}
	std::ifstream f;
	f.open(filename.c_str());
	if(!f.is_open())
		return false;

	char b[512];
	f.getline(b, 511);
	std::string line(b);

	int index = line.find("version");
	int qb = line.find_first_of("\"", index);
	int qe = line.find_first_of("\"", qb+1);
	version = line.substr(qb+1, qe-qb-1);

	Element* parent = NULL;
	
	while(!f.eof())
	{
		f.getline(b, 511);
		line = b;
		index = line.find_first_not_of(" \t");
		if(line[index] == '<')
		{
			int nb = line.find_first_not_of(" \t", index+1);
			if(line[nb] == '/')
			{
				if(parent->Get_parent())
					parent = parent->Get_parent();
				else
				{
					root = parent;
					break;
				}
			}
			else
			{
				int ne = line.find_first_of("> \t/", nb+1);
				std::string name = line.substr(nb, ne-nb);
				
				Element *element = new Element(name);

				while(!Check_end(ne, line))
				{
					int key_begin = line.find_first_not_of(" \t", ne+1);
					if(Check_end(key_begin, line)) break;
					int key_end = line.find_first_of("> \t/=", key_begin+1);
					if(Check_end(key_end, line)) break;

					int value_begin = line.find_first_of("\"", key_end+1);
					if(Check_end(value_begin, line)) break;
					int value_end = line.find_first_of("\"", value_begin+1);
					if(Check_end(value_end, line)) break;

					std::string key = line.substr(key_begin, key_end-key_begin);
					std::string value = line.substr(value_begin+1, value_end-value_begin-1);
					std::cout<<key<<"="<<value<<std::endl;
					element->Set_attribute(key, value);
					ne = value_end;
				}
				
				if(parent)
				{
					parent->Add_child(element);
				}
				parent = element;
			}
		}
		else if(parent)
		{
			int ne = line.find_last_not_of(" \t");
			std::string value = line.substr(index, ne-index+1);
			parent->Set_value(value);
		}
	}
	
	if(!root)
		delete parent;
	
	f.close();
	return true;
}