Exemplo n.º 1
0
void readVisualSceneInstanceGeometries(XMLDocument& doc, btHashMap<btHashString,int>& name2Shape, btAlignedObjectArray<ColladaGraphicsInstance>& visualShapeInstances)
{
	btHashMap<btHashString,XMLElement* > allVisualScenes;

	XMLElement* libVisualScenes = doc.RootElement()->FirstChildElement("library_visual_scenes");
	if (libVisualScenes==0)
		return;

	{
		for(XMLElement* scene = libVisualScenes->FirstChildElement("visual_scene");
				scene != NULL; scene = scene->NextSiblingElement("visual_scene")) 
		{
			const char* sceneName = scene->Attribute("id");
			allVisualScenes.insert(sceneName,scene);
		}
	}

	XMLElement* scene = 0;
	{
		XMLElement* scenes = doc.RootElement()->FirstChildElement("scene");
		if (scenes)
		{
			XMLElement* instanceSceneReference = scenes->FirstChildElement("instance_visual_scene");
			if (instanceSceneReference)
			{
				const char* instanceSceneUrl = instanceSceneReference->Attribute("url");
				XMLElement** sceneInstancePtr = allVisualScenes[instanceSceneUrl+1];//skip #
				if (sceneInstancePtr)
				{
					scene = *sceneInstancePtr;
				}
			}
		}
	}

	if (scene)
	{
		for(XMLElement* node = scene->FirstChildElement("node");
			node != NULL; node = node->NextSiblingElement("node")) 
		{
			btMatrix4x4 identity;
			identity.setIdentity();
			btVector3 identScaling(1,1,1);
			readNodeHierarchy(node,name2Shape,visualShapeInstances, identity);

		}
		
	}
}
REBOOL REXMLSerializableReader::Read(const REString & xmlString)
{
#ifndef __RE_NO_XML_PARSER_PRIVATE__	
	_totalElementsCount = 0;
	_processedElementsCount = 0;
	_isError = false;
	if (_controller && _callBack.CreateNewObject) 
	{
		XMLDocument doc;
		doc.Parse(xmlString.UTF8String());
		
		if (doc.Error()) { return false; }
		
		XMLElement * root = doc.RootElement();
		if (root == NULL) { return false; }
		
		const char * rootVal = root->Value();
		if (rootVal) 
		{
			if (strcmp(rootVal, "viewcontroller") == 0) 
			{
				_totalElementsCount = this->CalculateElements(root);
#if 0				
				if ( this->ParseObject(root, _controller, _controller) ) 
				{
					return true;
				}
#endif				
				_isError = true;
			}
		}
	}
#endif
	return false;
}
bool FractalConfiguration::readFractalID(string filename, string *id, string *error)
{
	XMLDocument doc;

	// Parse file
	doc.LoadFile(filename.c_str());

	if(doc.Error())
	{
		*error = doc.GetErrorStr1();
		return true;
	}

	// Get ID
	XMLElement *root = doc.RootElement();
	string name = string(root->Name());

	if(name != "fractal")
	{
		*error = "Configuration file is invalid!";
		return true;
	}

	const char* id_tmp = root->Attribute("id");

	if(id_tmp == NULL)
	{
		*error = "Configuration file is invalid!";
		return true;
	}

	*id = string(id_tmp);
	return false;
}
Exemplo n.º 4
0
void Partida::cargarNiveles() {
	XMLDocument doc;
	// abro XML correspondiente al mundo
	bool cargoArchivo = doc.LoadFile(this->rutaMundo);
	// Si no se cargo, lanzo error.
	if (cargoArchivo == false) {
		std::cout << "\tError al abrir el archivo XML." << std::endl;
		return;
	}

	// obtengo nodos 'Niveles'
	const XMLNode* nodo = doc.RootElement();
	nodo = nodo->FirstChildElement("Niveles");

	// Inicializo el contador de niveles
	int i = 1;
	// Cargo el primer nodo de nivel
	const XMLNode* nodoNivel = nodo->FirstChildElement("Nivel");
	// Mientras el nodo de nivel no es nulo, cargo los niveles.
	while (nodoNivel != 0) {
		// Obtengo el nodo con la ruta de archivo del nivel.
		const XMLNode* nodoRuta = nodoNivel->FirstChildElement("Ruta");
		// Si el nodo ruta no es nulo, cargo el nivel en la tabla
		if (nodoRuta != 0) {
			this->idNiveles[i] = nodoRuta->GetText();
			i++;  // Incremento el contador de niveles cargados
		}
		nodoNivel = nodoNivel->NextSiblingElement("Nivel");
	}
}
Exemplo n.º 5
0
void LoadScene::paeseXml()
{
    ValueVector xmlVector;
    
    //    //xml解析
    //string fileName="loadXml";
    //std::string filePath = FileUtils::getInstance()->getWritablePath() + fileName;
    
    //std::string filePath=cocos2d::FileUtils::getInstance()->getStringFromFile("loadPicture.xml");
    //获取文件在系统的绝对路径
    //std::string filePath1=FileUtils::getInstance()->fullPathForFilename("loadPicture.xml");
    //log("%s",filePath1.c_str());
    XMLDocument *pDoc = new XMLDocument();
    Data fileData=FileUtils::getInstance()->getDataFromFile("loadPicture.xml");
    pDoc->Parse((const char*)fileData.getBytes());//开始解析
    //    XMLError errorId = pDoc->LoadFile(filePath1.c_str());
    //    if (errorId != 0) {
    //        //xml格式错误
    //        log("cuowu");
    //    }
    //获取第一个节点属性
    XMLElement *rootEle = pDoc->RootElement();
    const XMLAttribute *attribute = rootEle->FirstAttribute();
    //打印节点属性名和值
    log("attribute<em>name = %s,attribute</em>value = %s", attribute->Name(), attribute->Value());
    
    loadXmlElement(rootEle);
    delete pDoc;
}
Exemplo n.º 6
0
bool ReverbsXml::LoadXml(string file)
{
    XMLDocument doc;
    XMLError e = doc.LoadFile(file.c_str());
    if (e != XML_SUCCESS)  return false;

    XMLElement* root = doc.RootElement();
    if (!root)  return false;

    //  clear
    revs.clear();
    revmap.clear();


    //  base
    XMLElement* b = root->FirstChildElement("base");
    if (b)
        GetParams(b, base);

    ///  revs
    int i=1;  //0 = none
    XMLElement* n = root->FirstChildElement("rev");
    while (n)
    {
        ReverbSet r;
        GetParams(n, r);

        revs.push_back(r);
        revmap[r.name] = i++;
        n = n->NextSiblingElement("rev");
    }
    return true;
}
Exemplo n.º 7
0
bool UserXml::LoadXml(std::string file)
{
	XMLDocument doc;
	XMLError e = doc.LoadFile(file.c_str());
	if (e != XML_SUCCESS)  return false;
		
	XMLElement* root = doc.RootElement();
	if (!root)  return false;

	//  clear
	trks.clear();  trkmap.clear();

	//  tracks
	const char* a;  //int i=1;  //0 = none
	XMLElement* eTrk = root->FirstChildElement("track");
	while (eTrk)
	{
		UserTrkInfo t;
		a = eTrk->Attribute("n");		if (a)  t.name = string(a);

		a = eTrk->Attribute("date");	if (a)  t.last = s2dt(a);
		a = eTrk->Attribute("rate");	if (a)  t.rating = s2i(a);
		a = eTrk->Attribute("laps");	if (a)  t.laps = s2i(a);
		a = eTrk->Attribute("time");	if (a)  t.time = s2r(a);

		trks.push_back(t);
		trkmap[t.name] = trks.size();  //i++;
		eTrk = eTrk->NextSiblingElement("track");
	}
	return true;
}
Exemplo n.º 8
0
TEST(XML_READER, CreateWithXMLDocument)
{
	XMLDocument * doc = XmlWrapper::loadDocument("UT/TestFiles/PDDB/test_pddb_2.xml");
	XMLElement * doc_element = doc->RootElement();
	XmlReader * reader = new XmlReader(doc);
	EXPECT_EQ(doc_element, reader->getCurrElement());
	delete reader;
	delete doc;
}
Exemplo n.º 9
0
  Maze* Maze::mazeFromXML(const std::string& filename) {
    Maze* newMaze = nullptr;

    try {
      XMLDocument doc;
      if (doc.LoadFile(filename.c_str()) == XML_SUCCESS) {
        XMLElement* root = doc.RootElement();

        if (!root || std::string(root->Name()).compare("maze") != 0) {
          throw std::runtime_error("Maze::mazeFromXML():  Not a maze file.");
        }

        XMLElement* floorElement = root->FirstChildElement("floor");
        if (!floorElement) {
          throw std::runtime_error("Maze::mazeFromXML():  Empty maze.");
        }

        newMaze = new Maze();

        while (floorElement && newMaze->getFloorCount() < Maze::MAX_FLOORS) {
          if (!floorElement->GetText()) {
            throw std::runtime_error("Maze::mazeFromXML():  Empty floor element.");
          }

          Map* floor = Map::mapFromXML(floorElement->GetText());
          if (!floor) {
            throw std::runtime_error("Maze::mazeFromXML():  Could not load a floor.");
          }

          newMaze->floors.push_back(floor);

          floorElement = floorElement->NextSiblingElement("floor");
        }
        
        if (floorElement) {
          //  There was more than MAX_FLOORS floors.  Best report it.
          writeToLog(MessageLevel::WARNING, "Maze::mazeFromXML():  More than 256 floors specified for the maze.  Stop this madness!");
        }
        
        newMaze->scanForEntrances();
      }
    }
    catch (std::exception& e) {
      if (newMaze) {
        delete newMaze;
        newMaze = nullptr;
      }

      writeToLog(MessageLevel::ERROR, "%s\n", e.what());
    }

    return newMaze;
  }
Exemplo n.º 10
0
std::string Partida::getPathImagenSuelo() {
	XMLDocument doc;
	bool cargoArchivo = doc.LoadFile(idNiveles[contadorNiveles]);
	if (cargoArchivo == false) {
		std::cout << "\tError al abrir el archivo XML." << std::endl;
		return std::string();
	}
	const XMLNode* nodo = doc.RootElement();
	const XMLNode* esc = nodo->FirstChildElement("Escenario");
	const XMLNode* imagenSuelo = esc->FirstChildElement("ImagenSuelo");
	return imagenSuelo->GetText();
}
Exemplo n.º 11
0
	void TriggerManager::LoadTriggersConfig(const std::string& moduleDir, std::vector<TriggerParameters>& trigsParams)
	{

		trigsParams.clear();

		std::string file(moduleDir + "triggersConfig.xml");

		XMLDocument doc;

		if(doc.LoadFile(file.c_str()) != XML_SUCCESS)
		{
			throw -1;
		}

		XMLElement* root = doc.RootElement();

		// Look for first trigger
		XMLElement* firstTrigger = root->FirstChildElement("Trigger");

		// Read all triggers
		for(XMLElement* trigger = firstTrigger; trigger != nullptr; trigger = trigger->NextSiblingElement())
		{
			TriggerParameters trigParams;

			// Get trigger id
			trigParams.sensorId = std::atoi(trigger->Attribute("sensorId"));

			// Get trigger type
			trigParams.type = Util::Enums::TriggerTypeFromString(trigger->Attribute("sensorType"));

			// Read xml elements
			XMLElement* threshold = trigger->FirstChildElement("Threshold");
			XMLElement* scanTime = trigger->FirstChildElement("ScanTime");
			XMLElement* maskTime = trigger->FirstChildElement("MaskTime");
			XMLElement* response = trigger->FirstChildElement("Response");

			trigParams.threshold = (short) std::atoi(threshold->GetText());
			trigParams.scanTime = (unsigned int) std::atoi(scanTime->GetText());
			trigParams.maskTime = std::atoi(maskTime->GetText());
			trigParams.response = Util::Enums::CurveTypeFromString(response->GetText());

			//XXX Reading only sensor type
			LoadSensorsConfig(moduleDir, trigParams.sensorType);
			//trigParams.sensorType = IO::SensorType::Hdd;

			trigsParams.push_back(trigParams);
		}


		return;
	}
Exemplo n.º 12
0
DecompositionPtr GraphMl::decompose(const Instance& instance) const
{
	using namespace tinyxml2;
	XMLDocument doc;
	if(doc.LoadFile(optFile.getValue().c_str()))
		error(doc.ErrorName());

	XMLElement* graphml = doc.RootElement();
	if(!graphml)
		error("No root element");

	XMLElement* graph = graphml->FirstChildElement("graph");
	if(!graph)
		error("No graph element");

	// XXX We assume the GraphML file has nodes and edges ordered as in a post-order traversal
	std::stack<DecompositionPtr> nodes;
	XMLElement* rootNode = graph->FirstChildElement("node");

	nodes.emplace(new Decomposition(bagOfNode(rootNode), app.getSolverFactory()));

	const XMLElement* element = rootNode;
	while((element = element->NextSiblingElement()) != nullptr) {
		if(strcmp(element->Name(), "node") == 0)
			nodes.emplace(new Decomposition(bagOfNode(element), app.getSolverFactory()));
		else if(strcmp(element->Name(), "edge") == 0) {
			if(nodes.size() < 2)
				error("Not enough nodes declared before edges");
			const DecompositionPtr to = nodes.top();
			nodes.pop();
			const DecompositionPtr& from = nodes.top();
			from->addChild(std::move(to));
		}
		else
			error("Unexpected element");
	}
	if(nodes.size() != 1)
		error("Not all non-root nodes connected to parents");

	DecompositionPtr root = nodes.top();

	if(optAddEmptyLeaves.isUsed())
		addEmptyLeaves(*root, app);
	if(optAddEmptyRoot.isUsed())
		root = addEmptyRoot(std::move(root), app);

	root->setRoot();
	return root;
}
Exemplo n.º 13
0
void PanelMundo::cargarNombreMundos() {
	/* En el directorio donde se encuentra el ejecutable, se almacenará un
	 * archivo donde se encuentran todos los mundos que ha creado el diseñador.
	 * Ese archivo se llamará "mundos.xml"
	 */
	XMLDocument doc;
	bool seAbrio = doc.LoadFile(pathFileMundos);
	// Si el archivo no existe, lo creo y salgo sin cargar mundos
	if (!seAbrio) {
		this->crearArchivoMundos();
		return;
	}

	// Obtengo el nodo raiz
	XMLNode* root = doc.RootElement();
	// Si es nulo, salgo sin realizar nada
	if (root == 0)
		return;

	// Obtengo el primer nodo del mundo
	const XMLNode* nodoMundo = root->FirstChildElement("Mundo");
	// Mientras el nodo de mundo no es nulo, cargo los mundos.
	while (nodoMundo != 0) {
		// Obtengo el nodo con el nombre del Mundo.
		const XMLNode* nodoNombre = nodoMundo->FirstChildElement("Nombre");
		std::string nombreMundo = nodoNombre->GetText();
		// Obtengo el atributo de la cantidad de jugadores
		int cantJugadores;
		const char* aCJ = nodoMundo->Attribute("cantJugadores", &cantJugadores);
		if (aCJ != 0) {
			std::string sCantJug = cfd::intToString(cantJugadores);
			nombreMundo += " (" + sCantJug;
			// Si la cantidad de jugadores es 1
			if (cantJugadores == 1) {
				nombreMundo += " jugador)";
			} else {
				nombreMundo += " jugadores)";
			}
		}
		// Obtengo el nodo con la ruta de archivo del mundo.
		const XMLNode* nodoRuta = nodoMundo->FirstChildElement("Ruta");
		// Si los nodos no son nulos, cargo el mundo a la tabla
		if ((nodoNombre != 0) && (nodoRuta != 0)) {
			nombreMundos[nombreMundo] = nodoRuta->GetText();
		}
		// Obtengo el siguiente nodo Mundo
		nodoMundo = nodoMundo->NextSiblingElement("Mundo");
	}
}
Exemplo n.º 14
0
void PanelEscenario::guardarCaracteristicasEscenario() const {
    // Abro el archivo asociado al nivel
    XMLDocument doc;
    doc.LoadFile(this->rutaNivel);
    // Obtengo el nodo raiz, que en teoria es el llamado Nivel.
    XMLNode* nivelNode = doc.RootElement();

    // Limpio el nodo de nivel
    this->limpiarNodoNivel(nivelNode);

    // Creo un nuevo nodo del escenario y cargo los atributos básicos.
    XMLNode* escenarioNode = new XMLNode("Escenario");
    // Convierto los valores flotantes a string.
    std::string sAncho = cfd::floatToString(anchoFlotante);
    std::string sAlto = cfd::floatToString(altoFlotante);
    // Seteo los atributos del nodo del escenario.
    escenarioNode->SetAttribute("ancho", sAncho);
    escenarioNode->SetAttribute("alto", sAlto);

    // Creo el nodo de la imagen del fondo.
    XMLNode* imageFondoNode = new XMLNode("ImagenFondo");
    XMLText* imageFondoText = new XMLText(rutaFondo);
    imageFondoNode->LinkEndChild(imageFondoText);

    // Creo el nodo de la imagen del suelo.
    XMLNode* imageSueloNode = new XMLNode("ImagenSuelo");
    // FIXME(eze) Esperar a que Tomás agrege el suelo para serializarlo en el XML.
    XMLText* imageSueloText = new XMLText(rutaSuelo);
    imageSueloNode->LinkEndChild(imageSueloText);

    // Creo el nodo con la cantidad de jugadores.
    XMLNode* jugadoresNode = new XMLNode("Jugadores");
    // Convierto el numero de jugadores a string.
    std::string sJugadores = cfd::intToString(cantidadJugadores);
    XMLText* jugadoresText = new XMLText(sJugadores);
    jugadoresNode->LinkEndChild(jugadoresText);

    // Linkeo los atributos del Escenario
    escenarioNode->LinkEndChild(imageFondoNode);
    escenarioNode->LinkEndChild(imageSueloNode);
    escenarioNode->LinkEndChild(jugadoresNode);

    // Linkeo el nodo de escenario en el nodo del nivel.
    nivelNode->LinkEndChild(escenarioNode);

    // Guardo el documento.
    doc.SaveFile();
}
Exemplo n.º 15
0
 Armature*   CCDragonBones::buildArmature(const char* skeletonXMLFile,
                                        const char* textureXMLFile,
                                        const char* dragonBonesName,
                                        const char* armatureName,
                                        const char* animationName)
 {
     XMLDataParser parser;
     XMLDocument doc;
     doc.LoadFile(skeletonXMLFile);
     Cocos2dxFactory fac;
     fac.addSkeletonData(parser.parseSkeletonData(doc.RootElement()) );
     XMLDocument doc1;
     doc1.LoadFile(textureXMLFile);
     fac.addTextureAtlas(new Cocos2dxTextureAtlas(parser.parseTextureAtlasData(doc1.RootElement())));
     return fac.buildArmature(armatureName, animationName ,dragonBonesName);
 }
Exemplo n.º 16
0
Level* LevelParser::parseLevel(const char* levelFile)
{
	// create a TinyXML document and load the XML level
	XMLDocument xmlDoc;
	if (xmlDoc.LoadFile(levelFile) != XML_SUCCESS)
	{
		std::cout << "Error: unable to load " << levelFile << std::endl;
		return nullptr;
	}

	// create the level object
	Level* pLevel = new Level();

	// get the root node
	XMLNode* pRoot = xmlDoc.RootElement();

	pRoot->ToElement()->QueryAttribute("tilewidth", &m_tileSize);
	pRoot->ToElement()->QueryAttribute("width", &m_width);
	pRoot->ToElement()->QueryAttribute("height", &m_height);
	pLevel->m_width = m_width;
	pLevel->m_height = m_height;
	pLevel->m_tileSize = m_tileSize;
	// Attribute() returns null if not found and std::string cannot be initialized with nullptr.
	const char* musicID = nullptr;
	musicID = pRoot->ToElement()->Attribute("musicID");
	if (musicID == nullptr) musicID = "";
	pLevel->setMusic(musicID);

	// parse object and tile layers
	for (XMLElement* e = pRoot->FirstChildElement(); e != NULL; e = e->NextSiblingElement())
	{
		if (e->Value() == std::string("objectgroup"))
		{
			parseObjLayer(e, pLevel);
		}
		else if (e->Value() == std::string("layer"))
		{
			parseTileLayer(e, pLevel);
		}
		else if (e->Value() == std::string("background"))
		{
			parseBckLayer(e, pLevel);
		}
	}

	return pLevel;
}
Exemplo n.º 17
0
MapSequence::MapSequence(const char* sequence_file):
	index(0)
{
	XMLDocument doc; 
	doc.LoadFile(sequence_file);
	auto map = doc.RootElement();
	auto node =map->FirstChildElement("Node");
	while(node)
	{
		auto left =node->FirstChildElement("Left");
		auto middle=node->FirstChildElement("Middle");
		auto right=node->FirstChildElement("Right"); 
		add(atoi (left->GetText()),atoi (middle->GetText()),atoi (right->GetText()));
		node=node->NextSiblingElement();
	}
	
}
Exemplo n.º 18
0
CModel*		CManagerModel::Load(string Path)
{
	for (auto it = mModelIndex.begin();it != mModelIndex.end(); it++) 
	{
		if (FSys.AliasAdd("Models",Path) == it->Path)
		{
			cout << "ManagerModel: Returning Allocated Buffer.\n";
			return it->Model;
		}
	}

	cout << "ManagerModel: Allocating New Buffer\n";


	CModel *Ret_Model = new CModel;
	
	Path = FSys.AliasAdd("Models",Path);
	XMLDocument doc;
	if (doc.LoadFile(Path.c_str()) ==  XML_SUCCESS)
	{
		XMLElement *Geo  = doc.RootElement()->FirstChildElement("library_geometries")->FirstChildElement("geometry");
		XMLElement *XMLMesh = Geo->FirstChildElement("mesh");

		while (Geo != NULL)
		{
			while (XMLMesh != NULL)
			{
				
				XMLMesh = ParseMesh(XMLMesh,Ret_Model);
			}
			Geo = Geo->NextSiblingElement();
		}
		cout << "Returned Valid Model.\n";

		Ret_Model->Finalize();
		mModelIndex.push_back(ModelPack(Ret_Model,Path));
		return Ret_Model;
	}
	else
	{
		Warning("Failed to load model: "+Path,true);
	}
	return NULL;

}
void BioAttributesContainer::load() {
	log->Write(INFO, "BioAttributesContainer:Loading attributes");

	std::string xmlFile = Global::Instance().getProperty("keymap_xml");

	XMLDocument doc;
	XMLError er = doc.LoadFile(xmlFile.c_str());

	if(er == XML_SUCCESS) {
		XMLElement * root = doc.RootElement();

		for(XMLElement * e = root->FirstChildElement(); e != NULL; e = e->NextSiblingElement()) {
			BioAttributeInfo info = parse(e);
			attrList.push_back(info);
		}
	}
	log->Write(INFO, "BioAttributesContainer:Loading end");
}
Exemplo n.º 20
0
void TR_svtImp::xmlParse(const string &set, vector< Ptr<Object> > &out)
{
    XMLDocument doc;
    doc.LoadFile(set.c_str());
    XMLElement *root_ = doc.RootElement();
    string rootElem(root_->Name());
    if (rootElem == "tagset")
    {
        string strImage("image");
        XMLElement *child = root_->FirstChildElement(strImage.c_str());
        while (child)
        {
            string imageName = child->FirstChildElement("imageName")->GetText();
            string lex = child->FirstChildElement("lex")->GetText();

            Ptr<TR_svtObj> curr(new TR_svtObj);
            curr->fileName = imageName;
            split(lex, curr->lex, ',');

            XMLElement *childTaggeds = child->FirstChildElement("taggedRectangles");
            if (childTaggeds)
            {
                string strTagged("taggedRectangle");
                XMLElement *childTagged = childTaggeds->FirstChildElement(strTagged.c_str());
                while (childTagged)
                {
                    tag t;
                    t.value = childTagged->FirstChildElement("tag")->GetText();
                    t.height = atoi(childTagged->Attribute("height"));
                    t.width = atoi(childTagged->Attribute("width"));
                    t.x = atoi(childTagged->Attribute("x"));
                    t.y = atoi(childTagged->Attribute("y"));
                    curr->tags.push_back(t);

                    childTagged = childTagged->NextSiblingElement(strTagged.c_str());
                }
            }

            out.push_back(curr);

            child = child->NextSiblingElement(strImage.c_str());
        }
    }
}
Exemplo n.º 21
0
void PanelMundo::actualizarArchivoMundos(const std::string rutaMundo) const {
	// Abro el archivo de los mundos
	XMLDocument doc;
	bool seAbrio = doc.LoadFile(pathFileMundos);
	// Si el archivo no existe, salgo
	if (!seAbrio)
		return;

	// Obtengo el nodo raiz
	XMLNode* root = doc.RootElement();
	// Si es nulo, salgo sin realizar nada
	if (root == 0)
		return;

	// Creo el nodo asociado al mundo
	XMLNode* nodoMundo = new XMLNode("Mundo");
	// Agrego el atributo de la cantidad de jugadores
	nodoMundo->SetAttribute("cantJugadores", creador->getCantidadJugadores());

	// Creo el nodo asociado al nombre del mundo
	XMLNode* nodoNombre = new XMLNode("Nombre");
	XMLText* textNombre = new XMLText(creador->getNombreElegido());
	nodoNombre->LinkEndChild(textNombre);

	// Creo el nodo asociado a al ruta del archivo que almacena el mundo
	XMLNode* nodoRuta = new XMLNode("Ruta");
	XMLText* textRuta = new XMLText(rutaMundo);
	nodoRuta->LinkEndChild(textRuta);

	// Linkeo los nodos de nombre y ruta al del mundo
	nodoMundo->LinkEndChild(nodoNombre);
	nodoMundo->LinkEndChild(nodoRuta);

	// Linkeo el nodo del nuevo mundo al nodo de mundos
	root->LinkEndChild(nodoMundo);

	// Guardo el archivo
	doc.SaveFile();
}
Exemplo n.º 22
0
static std::map<std::string, tank_t> get_tank_definitions() {
	XMLDocument doc;
	doc.Parse(get_tanks_xml_content("tanks.xml").c_str());

	XMLElement* root = doc.RootElement();

    std::map<std::string, tank_t> tanks;

    if (!root) {
        logger.writef(log_level_t::error, "Failed to load tanks.xml\n");
        return tanks;
    }

    for (XMLElement *node = root->FirstChildElement(); node; node = node->NextSiblingElement()) {
        if (!std::strcmp((const char*) node->Name(), "tank")) {
            tank_t tank = get_tank_definition(node);
            tanks[tank.icon] = tank;
        }
    }

    return tanks;
}
Exemplo n.º 23
0
	void TriggerManager::LoadSensorsConfig(const std::string& moduleDir, IO::SensorType& sensorType)
	{

		std::string file(moduleDir + "sensorsConfig.xml");

		XMLDocument doc;

		if(doc.LoadFile(file.c_str()) != XML_SUCCESS)
		{
			throw -1;
		}

		XMLElement* root = doc.RootElement();

		//XMLElement* samplingRate = root->FirstChildElement("SamplingRate");
		//XMLElement* resolution = root->FirstChildElement("Resolution");
		XMLElement* type = root->FirstChildElement("Type");

		sensorType = Util::Enums::SensorTypeFromString(type->GetText());

		return;
	}
Exemplo n.º 24
0
//  Load progress
//--------------------------------------------------------------------------------------------------------------------------------------
bool ProgressXml::LoadXml(std::string file)
{
	XMLDocument doc;
	XMLError e = doc.LoadFile(file.c_str());
	if (e != XML_SUCCESS)  return false;

	XMLElement* root = doc.RootElement();
	if (!root)  return false;

	//  clear
	chs.clear();

	const char* a;
	XMLElement* eCh = root->FirstChildElement("champ");
	while (eCh)
	{
		ProgressChamp pc;
		a = eCh->Attribute("name");		if (a)  pc.name = std::string(a);
		a = eCh->Attribute("ver");		if (a)  pc.ver = s2i(a);
		a = eCh->Attribute("cur");	if (a)  pc.curTrack = s2i(a);
		a = eCh->Attribute("p");	if (a)  pc.points = s2r(a);
		
		//  tracks
		XMLElement* eTr = eCh->FirstChildElement("t");
		while (eTr)
		{
			ProgressTrack pt;
			a = eTr->Attribute("p");	if (a)  pt.points = s2r(a);
			
			pc.trks.push_back(pt);
			eTr = eTr->NextSiblingElement("t");
		}

		chs.push_back(pc);
		eCh = eCh->NextSiblingElement("champ");
	}
	return true;
}
Exemplo n.º 25
0
void main() {
	cout << string("£¡ÏÔʾ").length();
	string line;
	int i = 0;
		char cCurrentPath[FILENAME_MAX];

		if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
		{
	//		return errno;
		}

		cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */

		printf("The current working directory is %s", cCurrentPath);
	ifstream myxml("LearnerDefs.xml");
		
	defs.clear();
	XMLDocument doc;
	if (doc.LoadFile("LearnerDefs.xml")==0) {
		doc.Print();
		XMLElement *root = doc.RootElement();
		for (XMLElement *child = root->FirstChildElement(); child; child = child->NextSiblingElement()) {
			Def *def = new Def();
			def->word = child->Attribute("word");
			def->creator = std::stoi(child->Attribute("creator"));
			def->definition = child->Value();
			defs.push_back(*def);			
			i++;
		}
	}
	list<Def>::iterator p;
	for (p = defs.begin(); p != defs.end(); p++) {
		cout << p->word << "," << p->definition << "," << p->creator << "\n";
	}
	getchar();
}
Exemplo n.º 26
0
void PanelEscenario::cargarCaracteristicasNivel() {
    /* Obtengo desde el archivo XML asociado al nivel, las caracteristicas del
     * mismo.
     */
    XMLDocument doc;
    doc.LoadFile(this->rutaNivel);
    const XMLNode* nivelNode = doc.RootElement();

    // Obtengo el nodo del escenario
    const XMLNode* escenarioNode = nivelNode->FirstChildElement("Escenario");

    // Si el nodo es nulo, seteo las dimenciones en tamaño medio y salgo
    if (escenarioNode == 0) {
        anchoFlotante = ANCHO_ESCENARIO_MEDIANO;
        altoFlotante = ALTO_ESCENARIO_MEDIANO;
        return;
    }

    // Obtengo los atributos de dimensiones del escenario.
    std::string sAncho = escenarioNode->Attribute("ancho");
    std::string sAlto = escenarioNode->Attribute("alto");

    // Seteo los atributos de dimensiones
    anchoFlotante = cfd::stringToFloat(sAncho);
    altoFlotante = cfd::stringToFloat(sAlto);

    // Obtengo el nodo de la imagen de fondo
    const XMLNode* imageFondoNode = escenarioNode->
                                    FirstChildElement("ImagenFondo");
    rutaFondo = imageFondoNode->GetText();

    // Obtengo el nodo de la imagen de suelo
    const XMLNode* imageSueloNode = escenarioNode->
                                    FirstChildElement("ImagenSuelo");
    rutaSuelo = imageSueloNode->GetText();
}
void SsdpDeviceScanner::getLocationData(string location, string uuid) {
	printf("getLocationData![%s][%s]\n", location.c_str(), uuid.c_str());

	if (mLocationDevice == NULL) {
		mLocationDevice = new LocationDevice();
	}

	if (mHttpClient == NULL) {
		mHttpClient = new CHttpClient();
	}

	string response;

	mHttpClient->Get(location, response);
	printf("getLocationData and response:[%s]\n", response.c_str());

	XMLDocument doc;
	doc.Parse(response.c_str());

    bool ok = true;

	XMLElement *root = doc.RootElement();
	XMLElement *URLBase = root->FirstChildElement("URLBase");
	if (URLBase != NULL) {
		mLocationDevice->url = URLBase->GetText();
		printf( "URLBase[%s]\n", URLBase->GetText());
	} else {
		ok = false;
	}

	XMLElement *device = root->FirstChildElement("device");
	if (device != NULL) {
		XMLElement *friendlyName = device->FirstChildElement("friendlyName");
		if (friendlyName) {
			mLocationDevice->friendlyName = friendlyName->GetText();
			printf("friendlyName![%s]\n", mLocationDevice->friendlyName.c_str());
		} else {
			ok = false;
		}
		
		XMLElement *manufacturer = device->FirstChildElement("manufacturer");
		if (manufacturer) {
			mLocationDevice->manufacturer = manufacturer->GetText();
			printf("manufacturer![%s]\n", mLocationDevice->manufacturer.c_str());
		} else {
			ok = false;
		}
		
		XMLElement *modelName = device->FirstChildElement("modelName");
		if (modelName) {
			mLocationDevice->modelName = modelName->GetText();
			printf("modelName![%s]\n", mLocationDevice->modelName.c_str());
		} else {
			ok = false;
		}

		// ignore icons
	}

	if (ok) {
		onResult(uuid, mLocationDevice);
	} else {
		mDiscoveredDeviceList.remove(uuid);
	}


}
Exemplo n.º 28
0
bool TMXSceneEncoder::parseTmx(const XMLDocument& xmlDoc, TMXMap& map, const string& inputDirectory) const
{
    const XMLElement* xmlMap = xmlDoc.FirstChildElement("map");
    if (!xmlMap)
    {
        LOG(1, "Missing root <map> element.\n");
        return false;
    }

    // Read in the map values //XXX should compact this so XML attribute parsing is a little nicer
    unsigned int uiValue;
    int iValue;
    const char* attValue = xmlMap->Attribute("width");
    sscanf(attValue, "%u", &uiValue);
    map.setWidth(uiValue);

    attValue = xmlMap->Attribute("height");
    sscanf(attValue, "%u", &uiValue);
    map.setHeight(uiValue);

    float fValue;
    attValue = xmlMap->Attribute("tilewidth");
    sscanf(attValue, "%f", &fValue);
    map.setTileWidth(fValue);

    attValue = xmlMap->Attribute("tileheight");
    sscanf(attValue, "%f", &fValue);
    map.setTileHeight(fValue);

    // Now we load all tilesets
    const XMLElement* xmlTileSet = xmlMap->FirstChildElement("tileset");
    while (xmlTileSet)
    {
        TMXTileSet tileSet;

        attValue = xmlTileSet->Attribute("firstgid");
        sscanf(attValue, "%u", &uiValue);
        tileSet.setFirstGid(uiValue);

        XMLDocument sourceXmlDoc;
        const XMLElement* xmlTileSetToLoad;
        attValue = xmlTileSet->Attribute("source");
        if (attValue)
        {
            XMLError err;
            string tsxLocation = buildFilePath(inputDirectory, attValue);
            if ((err = sourceXmlDoc.LoadFile(tsxLocation.c_str())) != XML_NO_ERROR)
            {
                LOG(1, "Could not load tileset's source TSX.\n");
                return false;
            }
            xmlTileSetToLoad = sourceXmlDoc.RootElement();
        }
        else
        {
            xmlTileSetToLoad = xmlTileSet;
        }

        // Maximum tile size
        attValue = xmlTileSetToLoad->Attribute("tilewidth");
        if (attValue)
        {
            sscanf(attValue, "%u", &uiValue);
            tileSet.setMaxTileWidth(uiValue);
        }
        else
        {
            tileSet.setMaxTileWidth(map.getTileWidth());
        }
        attValue = xmlTileSetToLoad->Attribute("tileheight");
        if (attValue)
        {
            sscanf(attValue, "%u", &uiValue);
            tileSet.setMaxTileHeight(uiValue);
        }
        else
        {
            tileSet.setMaxTileHeight(map.getTileHeight());
        }

        // Spacing and margin
        attValue = xmlTileSetToLoad->Attribute("spacing");
        if (attValue)
        {
            sscanf(attValue, "%u", &uiValue);
            tileSet.setSpacing(uiValue);
        }
        attValue = xmlTileSetToLoad->Attribute("margin");
        if (attValue)
        {
            sscanf(attValue, "%u", &uiValue);
            tileSet.setMargin(uiValue);
        }

        // Tile offset
        const XMLElement* xmlTileOffset = xmlTileSetToLoad->FirstChildElement("tileoffset");
        if (xmlTileOffset)
        {
            Vector2 offset;

            attValue = xmlTileOffset->Attribute("x");
            sscanf(attValue, "%d", &iValue);
            offset.x = iValue;
            attValue = xmlTileOffset->Attribute("y");
            sscanf(attValue, "%d", &iValue);
            offset.y = iValue;

            tileSet.setOffset(offset);
        }

        // Load image source. Don't worry about <data> or trans
        const XMLElement* xmlTileSetImage = xmlTileSetToLoad->FirstChildElement("image");
        if (!xmlTileSetImage)
        {
            LOG(1, "Could not find <image> element for tileset.\n");
            return false;
        }
        tileSet.setImagePath(xmlTileSetImage->Attribute("source"));

        if (xmlTileSetImage->Attribute("width") && xmlTileSetImage->Attribute("height"))
        {
            attValue = xmlTileSetImage->Attribute("width");
            sscanf(attValue, "%u", &uiValue);
            tileSet.setImageWidth(uiValue);

            attValue = xmlTileSetImage->Attribute("height");
            sscanf(attValue, "%u", &uiValue);
            tileSet.setImageHeight(uiValue);
        }
        else
        {
            // Load the image itself to get the width
            string imageLocation = buildFilePath(inputDirectory, tileSet.getImagePath());
            int pos = imageLocation.find_last_of('.');
            if (imageLocation.substr(pos).compare(".png") != 0)
            {
                LOG(1, "TileSet image must be a PNG. %s\n", imageLocation.c_str());
                return false;
            }

            Image* img = Image::create(imageLocation.c_str());
            if (!img)
            {
                LOG(1, "Could not load TileSet image. %s\n", imageLocation.c_str());
                return false;
            }
            tileSet.setImageWidth(img->getWidth());
            tileSet.setImageHeight(img->getHeight());
            SAFE_DELETE(img);
        }

        //TODO: tiles (specifically, tile animations) if possible. May require marking tiles as special tiles, and spinning them off to Sprites
        //<tile id="relId"><animation><frame tileid="relId" duration="numInMS"></...></...></...>

        // Save the tileset
        map.addTileSet(tileSet);

        xmlTileSet = xmlTileSet->NextSiblingElement("tileset");
    }

    // Load the layers
    const XMLElement* xmlLayer = xmlMap->FirstChildElement("layer");
    while (xmlLayer)
    {
        TMXLayer* layer = new TMXLayer();

        parseBaseLayerProperties(xmlLayer, layer);

        // Load properties
        attValue = xmlLayer->Attribute("width");
        if (attValue)
        {
            sscanf(attValue, "%u", &uiValue);
            layer->setWidth(uiValue);
        }
        else
        {
            layer->setWidth(map.getWidth());
        }

        attValue = xmlLayer->Attribute("height");
        if (attValue)
        {
            sscanf(attValue, "%u", &uiValue);
            layer->setHeight(uiValue);
        }
        else
        {
            layer->setHeight(map.getHeight());
        }

        // Load tiles
        layer->setupTiles();
        auto data = loadDataElement(xmlLayer->FirstChildElement("data"));
        size_t dataSize = data.size();
        for (int i = 0; i < dataSize; i++)
        {
            //XXX this might depend on map's renderorder... not sure
            unsigned int x = i % layer->getWidth();
            unsigned int y = i / layer->getWidth();
            layer->setTile(x, y, data[i]);
        }

        // Save layer
        map.addLayer(layer);

        xmlLayer = xmlLayer->NextSiblingElement("layer");
    }

    // Load image layers
    const XMLElement* xmlImgLayer = xmlMap->FirstChildElement("imagelayer");
    while (xmlImgLayer)
    {
        TMXImageLayer* imgLayer = new TMXImageLayer();

        parseBaseLayerProperties(xmlImgLayer, imgLayer);

        // Load properties
        attValue = xmlImgLayer->Attribute("x");
        if (attValue)
        {
            sscanf(attValue, "%d", &iValue);
            imgLayer->setX(iValue);
        }
        attValue = xmlImgLayer->Attribute("y");
        if (attValue)
        {
            sscanf(attValue, "%d", &iValue);
            imgLayer->setY(iValue);
        }

        // Load image source. Don't worry about <data>, trans, width, or height
        const XMLElement* xmlImage = xmlImgLayer->FirstChildElement("image");
        if (!xmlImage)
        {
            LOG(1, "Could not find <image> element for the image layer.\n");
            return false;
        }
        imgLayer->setImagePath(xmlImage->Attribute("source"));

        // Save image layer
        map.addLayer(imgLayer);

        xmlImgLayer = xmlImgLayer->NextSiblingElement("imagelayer");
    }

    return true;
}
Exemplo n.º 29
0
///  Load from xml
//-----------------------------------------------------------------------------------------------------
bool FollowCamera::loadCameras()
{
    fMoveTime = 5.f;  // hide hint on start

    miCount = 0;
    miCurrent = 0;
    Destroy();

    XMLDocument doc;
    XMLError e = doc.LoadFile((PATHMANAGER::Cars() + "/cameras.xml").c_str());
    if (e == XML_SUCCESS)
    {
        XMLElement* root = doc.RootElement();
        if (!root) {
            /*mErrorDialog->show(String("Error loading Cameras !!"), false );  return false;*/
        }
        XMLElement* cam = root->FirstChildElement("Camera");
        if (!cam) {
            /*mErrorDialog->show(String("Error loading Camera !!"), false );  return false;*/
        }

        while (cam)
        {
            CameraAngle* c = new CameraAngle();
            const char* a = 0;
            c->mName = cam->Attribute("name");
            c->mType = (CamTypes)s2i(cam->Attribute("type"));
            c->mYaw = Degree(0);
            c->mPitch = Degree(0);
            c->mDist = 10;
            c->mSpeed = 10;

            a = cam->Attribute("default");
            if (a)  if (s2i(a)==1)  miCurrent = miCount;
            a = cam->Attribute("on");
            if (a)  c->mMain = s2i(a)-1;
            a = cam->Attribute("hideGlass");
            if (a)  c->mHideGlass = s2i(a);

            a = cam->Attribute("yaw");
            if (a)  c->mYaw += Degree(s2r(a));
            a = cam->Attribute("pitch");
            if (a)  c->mPitch = Degree(s2r(a));
            a = cam->Attribute("dist");
            if (a)  c->mDist = s2r(a);
            a = cam->Attribute("offset");
            if (a)  c->mOffset = s2v(a);
            a = cam->Attribute("speed");
            if (a)  c->mSpeed = s2r(a);
            a = cam->Attribute("spRot");
            if (a)  c->mSpeedRot = s2r(a);
            else  c->mSpeedRot = c->mSpeed;
            a = cam->Attribute("bounce");
            if (a)  c->mOfsMul = s2r(a);

            if (c->mMain >= 0)  {
                mCameraAngles.push_back(c);
                miCount++;
            }
            else
                delete c;
            cam = cam->NextSiblingElement("Camera");
        }
    }

    miCount = mCameraAngles.size();
    if (miCount == 0)
    {
        CameraAngle* c = new CameraAngle();
        c->mName = "Follow Default";
        c->mType = CAM_Follow;
        c->mYaw = Degree(0);
        c->mPitch = Degree(14);
        c->mDist = 9;
        c->mOffset = Vector3(0,2,0);
        c->mSpeed = 15;
        mCameraAngles.push_back(c);
        miCount++;
    }

    updAngle();
    updFmtTxt();
    return true;
}
Exemplo n.º 30
0
int main( int argc, const char ** argv )
{
	#if defined( _MSC_VER ) && defined( DEBUG )
		_CrtMemCheckpoint( &startMemState );
	#endif

	#if defined(_MSC_VER) || defined(MINGW32) || defined(__MINGW32__)
		#if defined __MINGW64_VERSION_MAJOR && defined __MINGW64_VERSION_MINOR
			//MINGW64: both 32 and 64-bit
			mkdir( "resources/out/" );
                #else
                	_mkdir( "resources/out/" );
                #endif
	#else
		mkdir( "resources/out/", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
	#endif

	if ( argc > 1 ) {
		XMLDocument* doc = new XMLDocument();
		clock_t startTime = clock();
		doc->LoadFile( argv[1] );
		clock_t loadTime = clock();
		int errorID = doc->ErrorID();
		delete doc; doc = 0;
		clock_t deleteTime = clock();

		printf( "Test file '%s' loaded. ErrorID=%d\n", argv[1], errorID );
		if ( !errorID ) {
			printf( "Load time=%u\n",   (unsigned)(loadTime - startTime) );
			printf( "Delete time=%u\n", (unsigned)(deleteTime - loadTime) );
			printf( "Total time=%u\n",  (unsigned)(deleteTime - startTime) );
		}
		exit(0);
	}

	FILE* fp = fopen( "resources/dream.xml", "r" );
	if ( !fp ) {
		printf( "Error opening test file 'dream.xml'.\n"
				"Is your working directory the same as where \n"
				"the xmltest.cpp and dream.xml file are?\n\n"
	#if defined( _MSC_VER )
				"In windows Visual Studio you may need to set\n"
				"Properties->Debugging->Working Directory to '..'\n"
	#endif
			  );
		exit( 1 );
	}
	fclose( fp );

	XMLTest( "Example-1", 0, example_1() );
	XMLTest( "Example-2", 0, example_2() );
	XMLTest( "Example-3", 0, example_3() );
	XMLTest( "Example-4", true, example_4() );

	/* ------ Example 2: Lookup information. ---- */

	{
		static const char* test[] = {	"<element />",
										"<element></element>",
										"<element><subelement/></element>",
										"<element><subelement></subelement></element>",
										"<element><subelement><subsub/></subelement></element>",
										"<!--comment beside elements--><element><subelement></subelement></element>",
										"<!--comment beside elements, this time with spaces-->  \n <element>  <subelement> \n </subelement> </element>",
										"<element attrib1='foo' attrib2=\"bar\" ></element>",
										"<element attrib1='foo' attrib2=\"bar\" ><subelement attrib3='yeehaa' /></element>",
										"<element>Text inside element.</element>",
										"<element><b></b></element>",
										"<element>Text inside and <b>bolded</b> in the element.</element>",
										"<outer><element>Text inside and <b>bolded</b> in the element.</element></outer>",
										"<element>This &amp; That.</element>",
										"<element attrib='This&lt;That' />",
										0
		};
		for( int i=0; test[i]; ++i ) {
			XMLDocument doc;
			doc.Parse( test[i] );
			doc.Print();
			printf( "----------------------------------------------\n" );
		}
	}
#if 1
	{
		static const char* test = "<!--hello world\n"
								  "          line 2\r"
								  "          line 3\r\n"
								  "          line 4\n\r"
								  "          line 5\r-->";

		XMLDocument doc;
		doc.Parse( test );
		doc.Print();
	}

	{
		static const char* test = "<element>Text before.</element>";
		XMLDocument doc;
		doc.Parse( test );
		XMLElement* root = doc.FirstChildElement();
		XMLElement* newElement = doc.NewElement( "Subelement" );
		root->InsertEndChild( newElement );
		doc.Print();
	}
	{
		XMLDocument* doc = new XMLDocument();
		static const char* test = "<element><sub/></element>";
		doc->Parse( test );
		delete doc;
	}
	{
		// Test: Programmatic DOM
		// Build:
		//		<element>
		//			<!--comment-->
		//			<sub attrib="1" />
		//			<sub attrib="2" />
		//			<sub attrib="3" >& Text!</sub>
		//		<element>

		XMLDocument* doc = new XMLDocument();
		XMLNode* element = doc->InsertEndChild( doc->NewElement( "element" ) );

		XMLElement* sub[3] = { doc->NewElement( "sub" ), doc->NewElement( "sub" ), doc->NewElement( "sub" ) };
		for( int i=0; i<3; ++i ) {
			sub[i]->SetAttribute( "attrib", i );
		}
		element->InsertEndChild( sub[2] );
		XMLNode* comment = element->InsertFirstChild( doc->NewComment( "comment" ) );
		element->InsertAfterChild( comment, sub[0] );
		element->InsertAfterChild( sub[0], sub[1] );
		sub[2]->InsertFirstChild( doc->NewText( "& Text!" ));
		doc->Print();
		XMLTest( "Programmatic DOM", "comment", doc->FirstChildElement( "element" )->FirstChild()->Value() );
		XMLTest( "Programmatic DOM", "0", doc->FirstChildElement( "element" )->FirstChildElement()->Attribute( "attrib" ) );
		XMLTest( "Programmatic DOM", 2, doc->FirstChildElement()->LastChildElement( "sub" )->IntAttribute( "attrib" ) );
		XMLTest( "Programmatic DOM", "& Text!",
				 doc->FirstChildElement()->LastChildElement( "sub" )->FirstChild()->ToText()->Value() );

		// And now deletion:
		element->DeleteChild( sub[2] );
		doc->DeleteNode( comment );

		element->FirstChildElement()->SetAttribute( "attrib", true );
		element->LastChildElement()->DeleteAttribute( "attrib" );

		XMLTest( "Programmatic DOM", true, doc->FirstChildElement()->FirstChildElement()->BoolAttribute( "attrib" ) );
		int value = 10;
		int result = doc->FirstChildElement()->LastChildElement()->QueryIntAttribute( "attrib", &value );
		XMLTest( "Programmatic DOM", result, (int)XML_NO_ATTRIBUTE );
		XMLTest( "Programmatic DOM", value, 10 );

		doc->Print();

		{
			XMLPrinter streamer;
			doc->Print( &streamer );
			printf( "%s", streamer.CStr() );
		}
		{
			XMLPrinter streamer( 0, true );
			doc->Print( &streamer );
			XMLTest( "Compact mode", "<element><sub attrib=\"1\"/><sub/></element>", streamer.CStr(), false );
		}
		doc->SaveFile( "./resources/out/pretty.xml" );
		doc->SaveFile( "./resources/out/compact.xml", true );
		delete doc;
	}
	{
		// Test: Dream
		// XML1 : 1,187,569 bytes	in 31,209 allocations
		// XML2 :   469,073	bytes	in    323 allocations
		//int newStart = gNew;
		XMLDocument doc;
		doc.LoadFile( "resources/dream.xml" );

		doc.SaveFile( "resources/out/dreamout.xml" );
		doc.PrintError();

		XMLTest( "Dream", "xml version=\"1.0\"",
						  doc.FirstChild()->ToDeclaration()->Value() );
		XMLTest( "Dream", true, doc.FirstChild()->NextSibling()->ToUnknown() ? true : false );
		XMLTest( "Dream", "DOCTYPE PLAY SYSTEM \"play.dtd\"",
						  doc.FirstChild()->NextSibling()->ToUnknown()->Value() );
		XMLTest( "Dream", "And Robin shall restore amends.",
						  doc.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() );
		XMLTest( "Dream", "And Robin shall restore amends.",
						  doc.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() );

		XMLDocument doc2;
		doc2.LoadFile( "resources/out/dreamout.xml" );
		XMLTest( "Dream-out", "xml version=\"1.0\"",
						  doc2.FirstChild()->ToDeclaration()->Value() );
		XMLTest( "Dream-out", true, doc2.FirstChild()->NextSibling()->ToUnknown() ? true : false );
		XMLTest( "Dream-out", "DOCTYPE PLAY SYSTEM \"play.dtd\"",
						  doc2.FirstChild()->NextSibling()->ToUnknown()->Value() );
		XMLTest( "Dream-out", "And Robin shall restore amends.",
						  doc2.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() );

		//gNewTotal = gNew - newStart;
	}


	{
		const char* error =	"<?xml version=\"1.0\" standalone=\"no\" ?>\n"
							"<passages count=\"006\" formatversion=\"20020620\">\n"
							"    <wrong error>\n"
							"</passages>";

		XMLDocument doc;
		doc.Parse( error );
		XMLTest( "Bad XML", doc.ErrorID(), XML_ERROR_PARSING_ATTRIBUTE );
	}

	{
		const char* str = "<doc attr0='1' attr1='2.0' attr2='foo' />";

		XMLDocument doc;
		doc.Parse( str );

		XMLElement* ele = doc.FirstChildElement();

		int iVal, result;
		double dVal;

		result = ele->QueryDoubleAttribute( "attr0", &dVal );
		XMLTest( "Query attribute: int as double", result, (int)XML_NO_ERROR );
		XMLTest( "Query attribute: int as double", (int)dVal, 1 );
		result = ele->QueryDoubleAttribute( "attr1", &dVal );
		XMLTest( "Query attribute: double as double", result, (int)XML_NO_ERROR );
		XMLTest( "Query attribute: double as double", (int)dVal, 2 );
		result = ele->QueryIntAttribute( "attr1", &iVal );
		XMLTest( "Query attribute: double as int", result, (int)XML_NO_ERROR );
		XMLTest( "Query attribute: double as int", iVal, 2 );
		result = ele->QueryIntAttribute( "attr2", &iVal );
		XMLTest( "Query attribute: not a number", result, (int)XML_WRONG_ATTRIBUTE_TYPE );
		result = ele->QueryIntAttribute( "bar", &iVal );
		XMLTest( "Query attribute: does not exist", result, (int)XML_NO_ATTRIBUTE );
	}

	{
		const char* str = "<doc/>";

		XMLDocument doc;
		doc.Parse( str );

		XMLElement* ele = doc.FirstChildElement();

		int iVal, iVal2;
		double dVal, dVal2;

		ele->SetAttribute( "str", "strValue" );
		ele->SetAttribute( "int", 1 );
		ele->SetAttribute( "double", -1.0 );

		const char* cStr = ele->Attribute( "str" );
		ele->QueryIntAttribute( "int", &iVal );
		ele->QueryDoubleAttribute( "double", &dVal );

		ele->QueryAttribute( "int", &iVal2 );
		ele->QueryAttribute( "double", &dVal2 );

		XMLTest( "Attribute match test", ele->Attribute( "str", "strValue" ), "strValue" );
		XMLTest( "Attribute round trip. c-string.", "strValue", cStr );
		XMLTest( "Attribute round trip. int.", 1, iVal );
		XMLTest( "Attribute round trip. double.", -1, (int)dVal );
		XMLTest( "Alternate query", true, iVal == iVal2 );
		XMLTest( "Alternate query", true, dVal == dVal2 );
	}

	{
		XMLDocument doc;
		doc.LoadFile( "resources/utf8test.xml" );

		// Get the attribute "value" from the "Russian" element and check it.
		XMLElement* element = doc.FirstChildElement( "document" )->FirstChildElement( "Russian" );
		const unsigned char correctValue[] = {	0xd1U, 0x86U, 0xd0U, 0xb5U, 0xd0U, 0xbdU, 0xd0U, 0xbdU,
												0xd0U, 0xbeU, 0xd1U, 0x81U, 0xd1U, 0x82U, 0xd1U, 0x8cU, 0 };

		XMLTest( "UTF-8: Russian value.", (const char*)correctValue, element->Attribute( "value" ) );

		const unsigned char russianElementName[] = {	0xd0U, 0xa0U, 0xd1U, 0x83U,
														0xd1U, 0x81U, 0xd1U, 0x81U,
														0xd0U, 0xbaU, 0xd0U, 0xb8U,
														0xd0U, 0xb9U, 0 };
		const char russianText[] = "<\xD0\xB8\xD0\xBC\xD0\xB5\xD0\xB5\xD1\x82>";

		XMLText* text = doc.FirstChildElement( "document" )->FirstChildElement( (const char*) russianElementName )->FirstChild()->ToText();
		XMLTest( "UTF-8: Browsing russian element name.",
				 russianText,
				 text->Value() );

		// Now try for a round trip.
		doc.SaveFile( "resources/out/utf8testout.xml" );

		// Check the round trip.
		int okay = 0;

		FILE* saved  = fopen( "resources/out/utf8testout.xml", "r" );
		FILE* verify = fopen( "resources/utf8testverify.xml", "r" );

		if ( saved && verify )
		{
			okay = 1;
			char verifyBuf[256];
			while ( fgets( verifyBuf, 256, verify ) )
			{
				char savedBuf[256];
				fgets( savedBuf, 256, saved );
				NullLineEndings( verifyBuf );
				NullLineEndings( savedBuf );

				if ( strcmp( verifyBuf, savedBuf ) )
				{
					printf( "verify:%s<\n", verifyBuf );
					printf( "saved :%s<\n", savedBuf );
					okay = 0;
					break;
				}
			}
		}
		if ( saved )
			fclose( saved );
		if ( verify )
			fclose( verify );
		XMLTest( "UTF-8: Verified multi-language round trip.", 1, okay );
	}

	// --------GetText()-----------
	{
		const char* str = "<foo>This is  text</foo>";
		XMLDocument doc;
		doc.Parse( str );
		const XMLElement* element = doc.RootElement();

		XMLTest( "GetText() normal use.", "This is  text", element->GetText() );

		str = "<foo><b>This is text</b></foo>";
		doc.Parse( str );
		element = doc.RootElement();

		XMLTest( "GetText() contained element.", element->GetText() == 0, true );
	}


	// ---------- CDATA ---------------
	{
		const char* str =	"<xmlElement>"
								"<![CDATA["
									"I am > the rules!\n"
									"...since I make symbolic puns"
								"]]>"
							"</xmlElement>";
		XMLDocument doc;
		doc.Parse( str );
		doc.Print();

		XMLTest( "CDATA parse.", doc.FirstChildElement()->FirstChild()->Value(),
								 "I am > the rules!\n...since I make symbolic puns",
								 false );
	}

	// ----------- CDATA -------------
	{
		const char* str =	"<xmlElement>"
								"<![CDATA["
									"<b>I am > the rules!</b>\n"
									"...since I make symbolic puns"
								"]]>"
							"</xmlElement>";
		XMLDocument doc;
		doc.Parse( str );
		doc.Print();

		XMLTest( "CDATA parse. [ tixml1:1480107 ]", doc.FirstChildElement()->FirstChild()->Value(),
								 "<b>I am > the rules!</b>\n...since I make symbolic puns",
								 false );
	}

	// InsertAfterChild causes crash.
	{
		// InsertBeforeChild and InsertAfterChild causes crash.
		XMLDocument doc;
		XMLElement* parent = doc.NewElement( "Parent" );
		doc.InsertFirstChild( parent );

		XMLElement* childText0 = doc.NewElement( "childText0" );
		XMLElement* childText1 = doc.NewElement( "childText1" );

		XMLNode* childNode0 = parent->InsertEndChild( childText0 );
		XMLNode* childNode1 = parent->InsertAfterChild( childNode0, childText1 );

		XMLTest( "Test InsertAfterChild on empty node. ", ( childNode1 == parent->LastChild() ), true );
	}

	{
		// Entities not being written correctly.
		// From Lynn Allen

		const char* passages =
			"<?xml version=\"1.0\" standalone=\"no\" ?>"
			"<passages count=\"006\" formatversion=\"20020620\">"
				"<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;."
				" It also has &lt;, &gt;, and &amp;, as well as a fake copyright &#xA9;.\"> </psg>"
			"</passages>";

		XMLDocument doc;
		doc.Parse( passages );
		XMLElement* psg = doc.RootElement()->FirstChildElement();
		const char* context = psg->Attribute( "context" );
		const char* expected = "Line 5 has \"quotation marks\" and 'apostrophe marks'. It also has <, >, and &, as well as a fake copyright \xC2\xA9.";

		XMLTest( "Entity transformation: read. ", expected, context, true );

		FILE* textfile = fopen( "resources/out/textfile.txt", "w" );
		if ( textfile )
		{
			XMLPrinter streamer( textfile );
			psg->Accept( &streamer );
			fclose( textfile );
		}

        textfile = fopen( "resources/out/textfile.txt", "r" );
		TIXMLASSERT( textfile );
		if ( textfile )
		{
			char buf[ 1024 ];
			fgets( buf, 1024, textfile );
			XMLTest( "Entity transformation: write. ",
					 "<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;."
					 " It also has &lt;, &gt;, and &amp;, as well as a fake copyright \xC2\xA9.\"/>\n",
					 buf, false );
			fclose( textfile );
		}
	}

	{
		// Suppress entities.
		const char* passages =
			"<?xml version=\"1.0\" standalone=\"no\" ?>"
			"<passages count=\"006\" formatversion=\"20020620\">"
				"<psg context=\"Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;.\">Crazy &ttk;</psg>"
			"</passages>";

		XMLDocument doc( false );
		doc.Parse( passages );

		XMLTest( "No entity parsing.", doc.FirstChildElement()->FirstChildElement()->Attribute( "context" ),
				 "Line 5 has &quot;quotation marks&quot; and &apos;apostrophe marks&apos;." );
		XMLTest( "No entity parsing.", doc.FirstChildElement()->FirstChildElement()->FirstChild()->Value(),
				 "Crazy &ttk;" );
		doc.Print();
	}

	{
		const char* test = "<?xml version='1.0'?><a.elem xmi.version='2.0'/>";

		XMLDocument doc;
		doc.Parse( test );
		XMLTest( "dot in names", doc.Error(), false );
		XMLTest( "dot in names", doc.FirstChildElement()->Name(), "a.elem" );
		XMLTest( "dot in names", doc.FirstChildElement()->Attribute( "xmi.version" ), "2.0" );
	}

	{
		const char* test = "<element><Name>1.1 Start easy ignore fin thickness&#xA;</Name></element>";

		XMLDocument doc;
		doc.Parse( test );

		XMLText* text = doc.FirstChildElement()->FirstChildElement()->FirstChild()->ToText();
		XMLTest( "Entity with one digit.",
				 text->Value(), "1.1 Start easy ignore fin thickness\n",
				 false );
	}

	{
		// DOCTYPE not preserved (950171)
		//
		const char* doctype =
			"<?xml version=\"1.0\" ?>"
			"<!DOCTYPE PLAY SYSTEM 'play.dtd'>"
			"<!ELEMENT title (#PCDATA)>"
			"<!ELEMENT books (title,authors)>"
			"<element />";

		XMLDocument doc;
		doc.Parse( doctype );
		doc.SaveFile( "resources/out/test7.xml" );
		doc.DeleteChild( doc.RootElement() );
		doc.LoadFile( "resources/out/test7.xml" );
		doc.Print();

		const XMLUnknown* decl = doc.FirstChild()->NextSibling()->ToUnknown();
		XMLTest( "Correct value of unknown.", "DOCTYPE PLAY SYSTEM 'play.dtd'", decl->Value() );

	}

	{
		// Comments do not stream out correctly.
		const char* doctype =
			"<!-- Somewhat<evil> -->";
		XMLDocument doc;
		doc.Parse( doctype );

		XMLComment* comment = doc.FirstChild()->ToComment();

		XMLTest( "Comment formatting.", " Somewhat<evil> ", comment->Value() );
	}
	{
		// Double attributes
		const char* doctype = "<element attr='red' attr='blue' />";

		XMLDocument doc;
		doc.Parse( doctype );

		XMLTest( "Parsing repeated attributes.", XML_ERROR_PARSING_ATTRIBUTE, doc.ErrorID() );	// is an  error to tinyxml (didn't use to be, but caused issues)
		doc.PrintError();
	}

	{
		// Embedded null in stream.
		const char* doctype = "<element att\0r='red' attr='blue' />";

		XMLDocument doc;
		doc.Parse( doctype );
		XMLTest( "Embedded null throws error.", true, doc.Error() );
	}

	{
		// Empty documents should return TIXML_XML_ERROR_PARSING_EMPTY, bug 1070717
		const char* str = "    ";
		XMLDocument doc;
		doc.Parse( str );
		XMLTest( "Empty document error", XML_ERROR_EMPTY_DOCUMENT, doc.ErrorID() );
	}

	{
		// Low entities
		XMLDocument doc;
		doc.Parse( "<test>&#x0e;</test>" );
		const char result[] = { 0x0e, 0 };
		XMLTest( "Low entities.", doc.FirstChildElement()->GetText(), result );
		doc.Print();
	}

	{
		// Attribute values with trailing quotes not handled correctly
		XMLDocument doc;
		doc.Parse( "<foo attribute=bar\" />" );
		XMLTest( "Throw error with bad end quotes.", doc.Error(), true );
	}

	{
		// [ 1663758 ] Failure to report error on bad XML
		XMLDocument xml;
		xml.Parse("<x>");
		XMLTest("Missing end tag at end of input", xml.Error(), true);
		xml.Parse("<x> ");
		XMLTest("Missing end tag with trailing whitespace", xml.Error(), true);
		xml.Parse("<x></y>");
		XMLTest("Mismatched tags", xml.ErrorID(), XML_ERROR_MISMATCHED_ELEMENT);
	}


	{
		// [ 1475201 ] TinyXML parses entities in comments
		XMLDocument xml;
		xml.Parse("<!-- declarations for <head> & <body> -->"
				  "<!-- far &amp; away -->" );

		XMLNode* e0 = xml.FirstChild();
		XMLNode* e1 = e0->NextSibling();
		XMLComment* c0 = e0->ToComment();
		XMLComment* c1 = e1->ToComment();

		XMLTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true );
		XMLTest( "Comments ignore entities.", " far &amp; away ", c1->Value(), true );
	}

	{
		XMLDocument xml;
		xml.Parse( "<Parent>"
						"<child1 att=''/>"
						"<!-- With this comment, child2 will not be parsed! -->"
						"<child2 att=''/>"
					"</Parent>" );
		xml.Print();

		int count = 0;

		for( XMLNode* ele = xml.FirstChildElement( "Parent" )->FirstChild();
			 ele;
			 ele = ele->NextSibling() )
		{
			++count;
		}

		XMLTest( "Comments iterate correctly.", 3, count );
	}

	{
		// trying to repro ]1874301]. If it doesn't go into an infinite loop, all is well.
		unsigned char buf[] = "<?xml version=\"1.0\" encoding=\"utf-8\"?><feed><![CDATA[Test XMLblablablalblbl";
		buf[60] = 239;
		buf[61] = 0;

		XMLDocument doc;
		doc.Parse( (const char*)buf);
	}


	{
		// bug 1827248 Error while parsing a little bit malformed file
		// Actually not malformed - should work.
		XMLDocument xml;
		xml.Parse( "<attributelist> </attributelist >" );
		XMLTest( "Handle end tag whitespace", false, xml.Error() );
	}

	{
		// This one must not result in an infinite loop
		XMLDocument xml;
		xml.Parse( "<infinite>loop" );
		XMLTest( "Infinite loop test.", true, true );
	}
#endif
	{
		const char* pub = "<?xml version='1.0'?> <element><sub/></element> <!--comment--> <!DOCTYPE>";
		XMLDocument doc;
		doc.Parse( pub );

		XMLDocument clone;
		for( const XMLNode* node=doc.FirstChild(); node; node=node->NextSibling() ) {
			XMLNode* copy = node->ShallowClone( &clone );
			clone.InsertEndChild( copy );
		}

		clone.Print();

		int count=0;
		const XMLNode* a=clone.FirstChild();
		const XMLNode* b=doc.FirstChild();
		for( ; a && b; a=a->NextSibling(), b=b->NextSibling() ) {
			++count;
			XMLTest( "Clone and Equal", true, a->ShallowEqual( b ));
		}
		XMLTest( "Clone and Equal", 4, count );
	}

	{
		// This shouldn't crash.
		XMLDocument doc;
		if(XML_NO_ERROR != doc.LoadFile( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ))
		{
			doc.PrintError();
		}
		XMLTest( "Error in snprinf handling.", true, doc.Error() );
	}

	{
		// Attribute ordering.
		static const char* xml = "<element attrib1=\"1\" attrib2=\"2\" attrib3=\"3\" />";
		XMLDocument doc;
		doc.Parse( xml );
		XMLElement* ele = doc.FirstChildElement();

		const XMLAttribute* a = ele->FirstAttribute();
		XMLTest( "Attribute order", "1", a->Value() );
		a = a->Next();
		XMLTest( "Attribute order", "2", a->Value() );
		a = a->Next();
		XMLTest( "Attribute order", "3", a->Value() );
		XMLTest( "Attribute order", "attrib3", a->Name() );

		ele->DeleteAttribute( "attrib2" );
		a = ele->FirstAttribute();
		XMLTest( "Attribute order", "1", a->Value() );
		a = a->Next();
		XMLTest( "Attribute order", "3", a->Value() );

		ele->DeleteAttribute( "attrib1" );
		ele->DeleteAttribute( "attrib3" );
		XMLTest( "Attribute order (empty)", false, ele->FirstAttribute() ? true : false );
	}

	{
		// Make sure an attribute with a space in it succeeds.
		static const char* xml0 = "<element attribute1= \"Test Attribute\"/>";
		static const char* xml1 = "<element attribute1 =\"Test Attribute\"/>";
		static const char* xml2 = "<element attribute1 = \"Test Attribute\"/>";
		XMLDocument doc0;
		doc0.Parse( xml0 );
		XMLDocument doc1;
		doc1.Parse( xml1 );
		XMLDocument doc2;
		doc2.Parse( xml2 );

		XMLElement* ele = 0;
		ele = doc0.FirstChildElement();
		XMLTest( "Attribute with space #1", "Test Attribute", ele->Attribute( "attribute1" ) );
		ele = doc1.FirstChildElement();
		XMLTest( "Attribute with space #2", "Test Attribute", ele->Attribute( "attribute1" ) );
		ele = doc2.FirstChildElement();
		XMLTest( "Attribute with space #3", "Test Attribute", ele->Attribute( "attribute1" ) );
	}

	{
		// Make sure we don't go into an infinite loop.
		static const char* xml = "<doc><element attribute='attribute'/><element attribute='attribute'/></doc>";
		XMLDocument doc;
		doc.Parse( xml );
		XMLElement* ele0 = doc.FirstChildElement()->FirstChildElement();
		XMLElement* ele1 = ele0->NextSiblingElement();
		bool equal = ele0->ShallowEqual( ele1 );

		XMLTest( "Infinite loop in shallow equal.", true, equal );
	}

	// -------- Handles ------------
	{
		static const char* xml = "<element attrib='bar'><sub>Text</sub></element>";
		XMLDocument doc;
		doc.Parse( xml );

		XMLElement* ele = XMLHandle( doc ).FirstChildElement( "element" ).FirstChild().ToElement();
		XMLTest( "Handle, success, mutable", ele->Value(), "sub" );

		XMLHandle docH( doc );
		ele = docH.FirstChildElement( "none" ).FirstChildElement( "element" ).ToElement();
		XMLTest( "Handle, dne, mutable", false, ele != 0 );
	}

	{
		static const char* xml = "<element attrib='bar'><sub>Text</sub></element>";
		XMLDocument doc;
		doc.Parse( xml );
		XMLConstHandle docH( doc );

		const XMLElement* ele = docH.FirstChildElement( "element" ).FirstChild().ToElement();
		XMLTest( "Handle, success, const", ele->Value(), "sub" );

		ele = docH.FirstChildElement( "none" ).FirstChildElement( "element" ).ToElement();
		XMLTest( "Handle, dne, const", false, ele != 0 );
	}
	{
		// Default Declaration & BOM
		XMLDocument doc;
		doc.InsertEndChild( doc.NewDeclaration() );
		doc.SetBOM( true );

		XMLPrinter printer;
		doc.Print( &printer );

		static const char* result  = "\xef\xbb\xbf<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
		XMLTest( "BOM and default declaration", printer.CStr(), result, false );
		XMLTest( "CStrSize", printer.CStrSize(), 42, false );
	}
	{
		const char* xml = "<ipxml ws='1'><info bla=' /></ipxml>";
		XMLDocument doc;
		doc.Parse( xml );
		XMLTest( "Ill formed XML", true, doc.Error() );
	}

	// QueryXYZText
	{
		const char* xml = "<point> <x>1.2</x> <y>1</y> <z>38</z> <valid>true</valid> </point>";
		XMLDocument doc;
		doc.Parse( xml );

		const XMLElement* pointElement = doc.RootElement();

		int intValue = 0;
		unsigned unsignedValue = 0;
		float floatValue = 0;
		double doubleValue = 0;
		bool boolValue = false;

		pointElement->FirstChildElement( "y" )->QueryIntText( &intValue );
		pointElement->FirstChildElement( "y" )->QueryUnsignedText( &unsignedValue );
		pointElement->FirstChildElement( "x" )->QueryFloatText( &floatValue );
		pointElement->FirstChildElement( "x" )->QueryDoubleText( &doubleValue );
		pointElement->FirstChildElement( "valid" )->QueryBoolText( &boolValue );


		XMLTest( "QueryIntText", intValue, 1,						false );
		XMLTest( "QueryUnsignedText", unsignedValue, (unsigned)1,	false );
		XMLTest( "QueryFloatText", floatValue, 1.2f,				false );
		XMLTest( "QueryDoubleText", doubleValue, 1.2,				false );
		XMLTest( "QueryBoolText", boolValue, true,					false );
	}

	{
		const char* xml = "<element><_sub/><:sub/><sub:sub/><sub-sub/></element>";
		XMLDocument doc;
		doc.Parse( xml );
		XMLTest( "Non-alpha element lead letter parses.", doc.Error(), false );
	}
    
    {
        const char* xml = "<element _attr1=\"foo\" :attr2=\"bar\"></element>";
        XMLDocument doc;
        doc.Parse( xml );
        XMLTest("Non-alpha attribute lead character parses.", doc.Error(), false);
    }
    
    {
        const char* xml = "<3lement></3lement>";
        XMLDocument doc;
        doc.Parse( xml );
        XMLTest("Element names with lead digit fail to parse.", doc.Error(), true);
    }

	{
		const char* xml = "<element/>WOA THIS ISN'T GOING TO PARSE";
		XMLDocument doc;
		doc.Parse( xml, 10 );
		XMLTest( "Set length of incoming data", doc.Error(), false );
	}

    {
        XMLDocument doc;
        doc.LoadFile( "resources/dream.xml" );
        doc.Clear();
        XMLTest( "Document Clear()'s", doc.NoChildren(), true );
    }
    
	// ----------- Whitespace ------------
	{
		const char* xml = "<element>"
							"<a> This \nis &apos;  text  &apos; </a>"
							"<b>  This is &apos; text &apos;  \n</b>"
							"<c>This  is  &apos;  \n\n text &apos;</c>"
						  "</element>";
		XMLDocument doc( true, COLLAPSE_WHITESPACE );
		doc.Parse( xml );

		const XMLElement* element = doc.FirstChildElement();
		for( const XMLElement* parent = element->FirstChildElement();
			 parent;
			 parent = parent->NextSiblingElement() )
		{
			XMLTest( "Whitespace collapse", "This is ' text '", parent->GetText() );
		}
	}

#if 0
	{
		// Passes if assert doesn't fire.
		XMLDocument xmlDoc;

	    xmlDoc.NewDeclaration();
	    xmlDoc.NewComment("Configuration file");

	    XMLElement *root = xmlDoc.NewElement("settings");
	    root->SetAttribute("version", 2);
	}
#endif

	{
		const char* xml = "<element>    </element>";
		XMLDocument doc( true, COLLAPSE_WHITESPACE );
		doc.Parse( xml );
		XMLTest( "Whitespace  all space", true, 0 == doc.FirstChildElement()->FirstChild() );
	}

#if 0		// the question being explored is what kind of print to use: 
			// https://github.com/leethomason/tinyxml2/issues/63
	{
		const char* xml = "<element attrA='123456789.123456789' attrB='1.001e9'/>";
		XMLDocument doc;
		doc.Parse( xml );
		doc.FirstChildElement()->SetAttribute( "attrA", 123456789.123456789 );
		doc.FirstChildElement()->SetAttribute( "attrB", 1.001e9 );
		doc.Print();
	}
#endif

	{
		// An assert should not fire.
		const char* xml = "<element/>";
		XMLDocument doc;
		doc.Parse( xml );
		XMLElement* ele = doc.NewElement( "unused" );		// This will get cleaned up with the 'doc' going out of scope.
		XMLTest( "Tracking unused elements", true, ele != 0, false );
	}


	{
		const char* xml = "<parent><child>abc</child></parent>";
		XMLDocument doc;
		doc.Parse( xml );
		XMLElement* ele = doc.FirstChildElement( "parent")->FirstChildElement( "child");

		XMLPrinter printer;
		ele->Accept( &printer );
		XMLTest( "Printing of sub-element", "<child>abc</child>\n", printer.CStr(), false );
	}


	{
		XMLDocument doc;
		XMLError error = doc.LoadFile( "resources/empty.xml" );
		XMLTest( "Loading an empty file", XML_ERROR_EMPTY_DOCUMENT, error );
	}

	{
        // BOM preservation
        static const char* xml_bom_preservation  = "\xef\xbb\xbf<element/>\n";
        {
			XMLDocument doc;
			XMLTest( "BOM preservation (parse)", XML_NO_ERROR, doc.Parse( xml_bom_preservation ), false );
            XMLPrinter printer;
            doc.Print( &printer );

            XMLTest( "BOM preservation (compare)", xml_bom_preservation, printer.CStr(), false, true );
			doc.SaveFile( "resources/bomtest.xml" );
        }
		{
			XMLDocument doc;
			doc.LoadFile( "resources/bomtest.xml" );
			XMLTest( "BOM preservation (load)", true, doc.HasBOM(), false );

            XMLPrinter printer;
            doc.Print( &printer );
            XMLTest( "BOM preservation (compare)", xml_bom_preservation, printer.CStr(), false, true );
		}
	}

	{
		// Insertion with Removal
		const char* xml = "<?xml version=\"1.0\" ?>"
			"<root>"
			"<one>"
			"<subtree>"
			"<elem>element 1</elem>text<!-- comment -->"
			"</subtree>"
			"</one>"
			"<two/>"
			"</root>";
		const char* xmlInsideTwo = "<?xml version=\"1.0\" ?>"
			"<root>"
			"<one/>"
			"<two>"
			"<subtree>"
			"<elem>element 1</elem>text<!-- comment -->"
			"</subtree>"
			"</two>"
			"</root>";
		const char* xmlAfterOne = "<?xml version=\"1.0\" ?>"
			"<root>"
			"<one/>"
			"<subtree>"
			"<elem>element 1</elem>text<!-- comment -->"
			"</subtree>"
			"<two/>"
			"</root>";
		const char* xmlAfterTwo = "<?xml version=\"1.0\" ?>"
			"<root>"
			"<one/>"
			"<two/>"
			"<subtree>"
			"<elem>element 1</elem>text<!-- comment -->"
			"</subtree>"
			"</root>";

		XMLDocument doc;
		doc.Parse( xml );
		XMLElement* subtree = doc.RootElement()->FirstChildElement("one")->FirstChildElement("subtree");
		XMLElement* two = doc.RootElement()->FirstChildElement("two");
		two->InsertFirstChild(subtree);
		XMLPrinter printer1( 0, true );
		doc.Accept( &printer1 );
		XMLTest( "Move node from within <one> to <two>", xmlInsideTwo, printer1.CStr());

		doc.Parse( xml );
		subtree = doc.RootElement()->FirstChildElement("one")->FirstChildElement("subtree");
		two = doc.RootElement()->FirstChildElement("two");
		doc.RootElement()->InsertAfterChild(two, subtree);
		XMLPrinter printer2( 0, true );
		doc.Accept( &printer2 );
		XMLTest( "Move node from within <one> after <two>", xmlAfterTwo, printer2.CStr(), false );

		doc.Parse( xml );
		XMLNode* one = doc.RootElement()->FirstChildElement("one");
		subtree = one->FirstChildElement("subtree");
		doc.RootElement()->InsertAfterChild(one, subtree);
		XMLPrinter printer3( 0, true );
		doc.Accept( &printer3 );
		XMLTest( "Move node from within <one> after <one>", xmlAfterOne, printer3.CStr(), false );

		doc.Parse( xml );
		subtree = doc.RootElement()->FirstChildElement("one")->FirstChildElement("subtree");
		two = doc.RootElement()->FirstChildElement("two");
		doc.RootElement()->InsertEndChild(subtree);
		XMLPrinter printer4( 0, true );
		doc.Accept( &printer4 );
		XMLTest( "Move node from within <one> after <two>", xmlAfterTwo, printer4.CStr(), false );
	}

	// ----------- Performance tracking --------------
	{
#if defined( _MSC_VER )
		__int64 start, end, freq;
		QueryPerformanceFrequency( (LARGE_INTEGER*) &freq );
#endif

		FILE* fp  = fopen( "resources/dream.xml", "r" );
		fseek( fp, 0, SEEK_END );
		long size = ftell( fp );
		fseek( fp, 0, SEEK_SET );

		char* mem = new char[size+1];
		fread( mem, size, 1, fp );
		fclose( fp );
		mem[size] = 0;

#if defined( _MSC_VER )
		QueryPerformanceCounter( (LARGE_INTEGER*) &start );
#else
		clock_t cstart = clock();
#endif
		static const int COUNT = 10;
		for( int i=0; i<COUNT; ++i ) {
			XMLDocument doc;
			doc.Parse( mem );
		}
#if defined( _MSC_VER )
		QueryPerformanceCounter( (LARGE_INTEGER*) &end );
#else
		clock_t cend = clock();
#endif

		delete [] mem;

		static const char* note =
#ifdef DEBUG
			"DEBUG";
#else
			"Release";
#endif

#if defined( _MSC_VER )
		printf( "\nParsing %s of dream.xml: %.3f milli-seconds\n", note, 1000.0 * (double)(end-start) / ( (double)freq * (double)COUNT) );
#else
		printf( "\nParsing %s of dream.xml: %.3f milli-seconds\n", note, (double)(cend - cstart)/(double)COUNT );
#endif
	}

	#if defined( _MSC_VER ) &&  defined( DEBUG )
		_CrtMemCheckpoint( &endMemState );
		//_CrtMemDumpStatistics( &endMemState );

		_CrtMemState diffMemState;
		_CrtMemDifference( &diffMemState, &startMemState, &endMemState );
		_CrtMemDumpStatistics( &diffMemState );
		//printf( "new total=%d\n", gNewTotal );
	#endif

	printf ("\nPass %d, Fail %d\n", gPass, gFail);

	return gFail;
}