Example #1
0
void CharacterLoader::Load(TiXmlDocument& doc)
{
	TiXmlElement* root = doc.FirstChildElement("Body");
	root = root->FirstChildElement("Character");
	while (root)
	{
		TiXmlAttribute* attribute = root->FirstAttribute();
		std::string str = attribute->Name();
		if (str == "name")
		{
			std::string characterName = attribute->Value();
			std::string fileName;
			int x1 = -1, x2 = -1, y1 = -1, y2 = -1;
			TiXmlElement* element = root->FirstChildElement("a");
			
			while (element)
			{
				TiXmlAttribute* attrib = element->FirstAttribute();
				while (attrib)
				{
					std::string name = attrib->Name();
					std::string value = attrib->Value();
					addValue(characterName, name, value);

					attrib = attrib->Next();
				}
				element = element->NextSiblingElement("a");
			}

		}

		root = root->NextSiblingElement("Character");
	}
}
Example #2
0
void ImageLoader::Load(TiXmlDocument& doc)
{
	TiXmlElement* root = doc.FirstChildElement("Body");
	root = root->FirstChildElement("Image");
	while (root)
	{
		TiXmlAttribute* attribute = root->FirstAttribute();
		std::string str = attribute->Name();
		if (str == "name")
		{
			std::string imageName = attribute->Value();
			std::string fileName;
			int x1 = -1, x2 = -1, y1 = -1, y2 = -1;
			TiXmlElement* element = root->FirstChildElement("a");
			if (element)
			{
				if (element->Attribute("file"))
				{
					fileName = element->Attribute("file");
				}
			}

			element = root->FirstChildElement("rect");

			while (element)
			{

				TiXmlAttribute* attrib = element->FirstAttribute();
				while (attrib)
				{
					std::string name = attrib->Name();
					if (name == "x1")
					{
						x1 = attrib->IntValue();
					}
					else if (name == "x2")
					{
						x2 = attrib->IntValue();
					}
					else if (name == "y1")
					{
						y1 = attrib->IntValue();
					}
					else if (name == "y2")
					{
						y2 = attrib->IntValue();
					}

					attrib = attrib->Next();
				}
				element = element->NextSiblingElement("rect");
			}

			internalCreate(imageName, fileName, x1, y1, x2, y2);
		}

		root = root->NextSiblingElement("Image");
	}
}
bool wxsItemResData::RebuildXrcFile()
{
    // First - opening file
    TiXmlDocument Doc;
    TiXmlElement* Resources = nullptr;
    TiXmlElement* Object = nullptr;

    if ( TinyXML::LoadDocument(m_XrcFileName,&Doc) )
    {
        Resources = Doc.FirstChildElement("resource");
    }

    if ( !Resources )
    {
        Doc.Clear();
        Doc.InsertEndChild(TiXmlDeclaration("1.0","utf-8",""));
        Resources = Doc.InsertEndChild(TiXmlElement("resource"))->ToElement();
        Resources->SetAttribute("xmlns","http://www.wxwidgets.org/wxxrc");
    }

    // Searching for object representing this resource
    for ( Object = Resources->FirstChildElement("object"); Object; Object = Object->NextSiblingElement("object") )
    {
        if ( cbC2U(Object->Attribute("name")) == m_ClassName )
        {
            Object->Clear();
            while ( Object->FirstAttribute() )
            {
                Object->RemoveAttribute(Object->FirstAttribute()->Name());
            }
            break;
        }
    }

    if ( !Object )
    {
        Object = Resources->InsertEndChild(TiXmlElement("object"))->ToElement();
    }

    // The only things left are: to dump item into object ...
    m_RootItem->XmlWrite(Object,true,false);
    Object->SetAttribute("name",cbU2C(m_ClassName));
    for ( int i=0; i<GetToolsCount(); i++ )
    {
        TiXmlElement* ToolElement = Object->InsertEndChild(TiXmlElement("object"))->ToElement();
        m_Tools[i]->XmlWrite(ToolElement,true,false);
    }

    // ... and save back the file
    return TinyXML::SaveDocument(m_XrcFileName,&Doc);
}
Example #4
0
void MeshCompiler::CompileAnimations( TiXmlElement* Arm )
{
	// Get named animations from the keyframes
	for( TiXmlElement* Keyf = Arm->FirstChildElement( "anim" ); Keyf; Keyf = Keyf->NextSiblingElement( "anim" ) )
	{
		Animation Animation;

		// Get starting frame and name (patch up lengths later)
		TiXmlAttribute* KeyfAttr = Keyf->FirstAttribute();
		Animation.m_StartFrame = (uint16)KeyfAttr->IntValue();

		KeyfAttr = KeyfAttr->Next();
		const char* pName = KeyfAttr->Value();
		CleanStrncpy( Animation.m_Name, pName, ANIM_NAME_LENGTH );
		Animation.m_HashedName = Animation.m_Name;

		m_Animations.PushBack( Animation );
		++m_Header.m_NumAnims;
	}
	for( int i = 0; i < ( m_Header.m_NumAnims - 1 ); ++i )
	{
		Animation& ThisAnim = m_Animations[ i ];
		Animation& NextAnim = m_Animations[ i + 1 ];
		ThisAnim.m_Length = NextAnim.m_StartFrame - ThisAnim.m_StartFrame;
	}
	// Patch up the last animation's length separately
	if( m_Header.m_NumAnims )
	{
		Animation& ThisAnim = m_Animations[ m_Header.m_NumAnims - 1 ];
		ThisAnim.m_Length = (uint16)( ( m_Header.m_NumFrames ) - ThisAnim.m_StartFrame );	// -1 because of added T-pose
	}
}
Example #5
0
bool ReadXmlFile(std::string& szFileName)
{//读取Xml文件,并遍历
	try
	{
		std::string fullPath = GetAppPath();
		fullPath += "\\";
		fullPath += szFileName;
		//创建一个XML的文档对象。
		TiXmlDocument *myDocument = new TiXmlDocument(fullPath.c_str());
		myDocument->LoadFile();
		//获得根元素,即Persons。
		TiXmlElement *RootElement = myDocument->RootElement();
		//输出根元素名称,即输出Persons。
		std::cout << RootElement->Value() << std::endl;
		//获得第一个Person节点。
		TiXmlElement *FirstPerson = RootElement->FirstChildElement();
		//获得第一个Person的name节点和age节点和ID属性。
		TiXmlElement *NameElement = FirstPerson->FirstChildElement();
		TiXmlElement *AgeElement = NameElement->NextSiblingElement();
		TiXmlAttribute *IDAttribute = FirstPerson->FirstAttribute();
		//输出第一个Person的name内容,即周星星;age内容,即;ID属性,即。
		std::cout << NameElement->FirstChild()->Value() << std::endl;
		std::cout << AgeElement->FirstChild()->Value() << std::endl;
		std::cout << IDAttribute->Value()<< std::endl;
	}
	catch (std::string& e)
	{
		return false;
	}
	return true;
}
void HelloWorld::parseTinyXmlFile()
{
	try
	{
		char filePath[1024]= {'\0'};
		memset(filePath,0,sizeof(filePath));
		strcat(filePath,CCFileUtils::sharedFileUtils()->getWriteablePath().c_str());
		strcat(filePath,"CreatedTinyXml.xml");

		//创建一个XML的文档对象。
		TiXmlDocument *myDocument = new TiXmlDocument(filePath);
		myDocument->LoadFile();
		//获得根元素,即Persons。
		TiXmlElement *RootElement = myDocument->RootElement();
		//输出根元素名称,即输出Persons。
		CCLOG(RootElement->Value());
		//获得第一个Person节点。
		TiXmlElement *FirstPerson = RootElement->FirstChildElement();
		//获得第一个Person的name节点和age节点和ID属性。
		TiXmlElement *NameElement = FirstPerson->FirstChildElement();
		TiXmlElement *AgeElement = NameElement->NextSiblingElement();
		TiXmlAttribute *IDAttribute = FirstPerson->FirstAttribute();
		//输出第一个Person的name内容,即周星星;age内容,即;ID属性,即。

		CCLOG(NameElement->FirstChild()->Value());
		CCLOG(AgeElement->FirstChild()->Value());
		CCLOG(IDAttribute->Value());
	}
	catch (string& e)
	{
		return ;
	}
	return ;
}
Example #7
0
/**
* 从xml文件中读取“键-值”对 load "key-value" from xml file
* @param filename 读取的xml文件,必须是按照规定的格式
* @return 布尔值 读取成功与否
*/
bool Properties::loadFromXML(const string filename)
{
	TiXmlDocument doc(filename.c_str());
	bool loadOkay = doc.LoadFile();//以utf-8格式读取xml文件
	if (!loadOkay)
	{
		return false;
	}
	TiXmlNode *node = doc.FirstChild("properties");
        #ifdef DEBUG_PROPERTIES_H
	node->Print(stdout, 1);
	cout << endl;
        #endif
	TiXmlElement* propertiesElement = node->ToElement();
	for(TiXmlElement *it = propertiesElement->FirstChildElement("entry")
		; it!=NULL ;
		it = it->NextSiblingElement("entry")
		)
	{
		TiXmlAttribute *att = it->FirstAttribute();
		this->setProperty(att->Value(), it->GetText());
		#ifdef DEBUG_PROPERTIES_H
		cout << "[" << att->Name() << ":" << att->Value() << "->" << it->GetText() << "]" << endl;
                #endif
	}
	return true;
}
Example #8
0
bool SSHTablesConfig::Parse(string xmlFile) {
	TiXmlDocument *doc = new TiXmlDocument(xmlFile.c_str());
    if (doc->LoadFile()) {
		TiXmlElement *root = doc->RootElement();
		TiXmlElement *pack = root->FirstChildElement();
		while (pack != NULL) {
			if (string(pack->Value()) == "package-path") {
				packagePath = pack->GetText();
			}

			if (string(pack->Value()) == "tables") {
				TiXmlElement *t = pack->FirstChildElement();
				while (t != NULL) {
					if (string(t->Value()) == "table") {
						Table table;
						TiXmlElement *tb = t->FirstChildElement();
						while (tb != NULL) {	
							if (string(tb->Value()) == "name") {
								table.name = tb->GetText();
							}
							if (string(tb->Value()) == "schema") {
								table.schema = tb->GetText();
							}
							if (string(tb->Value()) == "objectName") {
								table.objectName = tb->GetText();
							}

							if (string(tb->Value()) == "columns") {
								TiXmlElement *col = tb->FirstChildElement();
								while (col != NULL) {
									if (string(col->Value()) == "column") {
										Column column = {"undefined", "undefined"};
										column.name = col->GetText();
										TiXmlAttribute *attr = col->FirstAttribute();
										while (attr != NULL) {
											if (string(attr->Name()) == "type") {
												column.type = attr->Value();
											}
											attr = attr->Next();
										}
										table.columns.push_back(column);
									}
									col = col->NextSiblingElement();
								}
							}
							tb = tb->NextSiblingElement();
						}
						t = t->NextSiblingElement();
						tables.push_back(table);
					}
				}
			}
			pack = pack->NextSiblingElement();
		}
		return true;
	}  
	return false;
}
Example #9
0
void MeshCompiler::CompileArmature( TiXmlElement* Arm )
{
	if( Arm )
	{
		m_Header.m_HasSkeleton = true;
		TiXmlAttribute* ArmAttr = Arm->FirstAttribute();	// "frames"
		m_Header.m_NumFrames = ArmAttr->IntValue() + 1;	// + 1 for T-pose at frame 0
		for( TiXmlElement* Bone = Arm->FirstChildElement( "bonedef" ); Bone; Bone = Bone->NextSiblingElement( "bonedef" ) )
		{
			SNamedBone sbone;
			TiXmlAttribute* BoneAttr = Bone->FirstAttribute();
			const char* pName = BoneAttr->Value();
			sbone.m_Name = HashedString( pName );

			// Push an identity so frame 0 is the T-pose
			sbone.m_FrameQuats.PushBack( Quat() );
			sbone.m_FrameTransVecs.PushBack( Vector() );

			for( TiXmlElement* Frame = Bone->FirstChildElement( "frame" ); Frame; Frame = Frame->NextSiblingElement( "frame" ) )
			{
				Matrix FrameMatrix;
				TiXmlAttribute* FrameAttr = Frame->FirstAttribute();

				// In case I ever need separate frame values
				int FrameNum = FrameAttr->IntValue();
				Unused( FrameNum );

				FrameAttr = FrameAttr->Next();
				GetXMLMatrix( FrameAttr, FrameMatrix );

				Quat FrameQuat = FrameMatrix.ToQuaternion();
				Vector FrameTransVec = FrameMatrix.GetTranslationElements();

				sbone.m_FrameQuats.PushBack( FrameQuat );
				sbone.m_FrameTransVecs.PushBack( FrameTransVec );
			}

			m_Bones.PushBack( sbone );
			++m_Header.m_NumBones;
		}

		CompileAnimations( Arm );
	}
}
Example #10
0
int em::EmXml::ClearRootAttr()
{
	bool bUpdated = false;
	int iResult = 0;
	TiXmlElement *pElemRoot = m_pDoc->RootElement();
	if(pElemRoot == NULL)
	{
		return 0;
	}
	
	
	while(pElemRoot->FirstAttribute())
	{
		pElemRoot->RemoveAttribute(pElemRoot->FirstAttribute()->Name());
		bUpdated = true;
	}

	m_bUpdated = bUpdated;
	return iResult;
}
Example #11
0
void DataModel::loadStage()
{
    TiXmlDocument* myDocument = new TiXmlDocument();
    unsigned char* pBuffer = NULL;
    ssize_t bufferSize = 0;
    pBuffer = FileUtils::getInstance()->getFileData("stage.xml", "r", &bufferSize);
    if (pBuffer) {
        myDocument->Parse((const char*)pBuffer);
        TiXmlElement* stage = myDocument->RootElement();
        TiXmlElement* points = stage->FirstChildElement();
        TiXmlElement* point = points->FirstChildElement();
        while (points) {
            const char *name = points->Attribute("name");
            __Array *temp = __Array::create();
            
            while (point) {
                TiXmlAttribute *x = point->FirstAttribute();
                int pointX = x->IntValue();
                int pointY = x->Next()->IntValue();
                if (_winSize.height < 1100) {
                    pointY = pointY - 25;
                }
                temp->addObject(new MyPoint(pointX ,_winSize.height / 1280.0 * pointY));
                point = point->NextSiblingElement();
            }
            if (StringUtils::format("s9%d",flag9) == std::string(name)) {
                stage9.pushBack(temp);
                flag9++;
            }
            if (StringUtils::format("s5%d",flag5) == std::string(name)) {
                stage5.pushBack(temp);
                flag5++;
            }
            if (StringUtils::format("s6%d",flag6) == std::string(name)) {
                stage6.pushBack(temp);
                flag6++;
            }
            point = points->FirstChildElement();
            points = points->NextSiblingElement();
        }
        Ref *obj;
        MyPoint *p;
        for (auto a: stage5) {
            
            CCARRAY_FOREACH(a, obj)
            {
                p = (MyPoint *)obj;
            }
            
        }

    }
 
}
Example #12
0
int em::EmXml::ReadRootChildAttrList( EmVecMapStr &rVecMapStr )
{
	int iResult = 0;
	rVecMapStr.clear();

	TiXmlElement *pElemRoot = m_pDoc->RootElement();
	if(pElemRoot == NULL)
	{
		return 0;
	}
	
	TiXmlElement *pElemChild = pElemRoot->FirstChildElement();
	TiXmlAttribute *pAttrChild = NULL;
	EmMapStr MapStr;
	while(true)
	{
		if(pElemChild == NULL)
		{
			break;
		}
		
		if(pElemChild->Type() != TiXmlNode::TINYXML_ELEMENT)
		{
			continue;
		}
		
		MapStr.clear();
		
		pAttrChild = pElemChild->FirstAttribute();
		while(true)
		{
			if(pAttrChild == NULL)
			{
				break;
			}
			
			MapStr[ pAttrChild->Name() ] = pAttrChild->Value();
			
			pAttrChild = pAttrChild->Next();
		}
		
		rVecMapStr.push_back(MapStr);
		pElemChild = pElemChild->NextSiblingElement();
	}
	
	iResult = rVecMapStr.size();
	
	return iResult;
}
Example #13
0
void BulletMLParserTinyXML::translateNode(TiXmlNode* node) {
    TiXmlElement* elem = node->ToElement();
    assert(elem != 0);

    BulletMLNode* xmlNode = addContent(elem->Value());

    if (xmlNode->getName() == BulletMLNode::bulletml) {
        TiXmlAttribute* attr;
        for (attr = elem->FirstAttribute(); attr; attr = attr->Next()) {
            if (attr->Value() == "horizontal") setHorizontal();
        }
    }
    else {
        MyAttributes mattr;
        TiXmlAttribute* attr;
        for (attr = elem->FirstAttribute(); attr; attr = attr->Next()) {
            mattr.push_back(attr->Name());
            mattr.push_back(attr->Value());
        }
        addAttribute(mattr, xmlNode);
        if (curNode_ != 0) curNode_->addChild(xmlNode);
    }
    curNode_ = xmlNode;
}
Example #14
0
int em::EmXml::ReadRootChildAttrMap( const char* szKeyName, const char* szKeyValue, EmMapStr &rMapStr )
{
	int iResult = 0;
	rMapStr.clear();

	TiXmlElement *pElemRoot = m_pDoc->RootElement();
	if(pElemRoot == NULL)
	{
		return 0;
	}
	
	TiXmlElement *pElemChild = pElemRoot->FirstChildElement();
	TiXmlAttribute *pAttrChild = NULL;
	while(true)
	{
		if(pElemChild == NULL)
		{
			break;
		}
		
		if(pElemChild->Type() != TiXmlNode::TINYXML_ELEMENT)
		{
			continue;
		}
		
		if(EmSz::Equal( pElemChild->Attribute( szKeyName) , szKeyValue))
		{
			pAttrChild = pElemChild->FirstAttribute();
			while(true)
			{
				if(pAttrChild == NULL)
				{
					break;
				}
				
				rMapStr[  pAttrChild->Name() ] = pAttrChild->Value();
				pAttrChild = pAttrChild->Next();
			}
			break;
		}
		
		pElemChild = pElemChild->NextSiblingElement();
	}
	iResult = rMapStr.size();
	
	return iResult;
}
Example #15
0
int em::EmXml::RemoveRootChild( const char* szChildName, const char* szKeyName, const char* szKeyValue )
{
	bool bUpdated = false;
	int iResult = 0;

	TiXmlElement *pElemRoot = m_pDoc->RootElement();
	if(pElemRoot == NULL)
	{
		return 0;
	}
	
	TiXmlElement *pElemChild = pElemRoot->FirstChildElement();
	TiXmlAttribute *pAttrChild = NULL;
	
	while(true)
	{
		if(pElemChild == NULL)
		{
			break;
		}
		
		if(pElemChild->Type() != TiXmlNode::TINYXML_ELEMENT)
		{
			continue;
		}
		
		pAttrChild = pElemChild->FirstAttribute();
		
		if(EmSz::Equal( pElemChild->Attribute( szKeyName ), szKeyValue))
		{
			if(EmSz::Equal(pElemChild->Value(),szChildName))
			{
				pElemRoot->RemoveChild(pElemChild);
				bUpdated = true;
				break;
			}
			
		}
		
		pElemChild = pElemChild->NextSiblingElement();
	}

	m_bUpdated = bUpdated;

	return iResult;
}
Example #16
0
int em::EmXml::WriteRootChildAttrMap( const char* szKeyName, const char* szKeyValue, EmMapStr &rMapStr )
{
	std::string strResult;
	bool bUpdated = false;
	int iResult = 0;

	TiXmlElement *pElemRoot = m_pDoc->RootElement();
	if(pElemRoot == NULL)
	{
		return 0;
	}
	
	TiXmlElement *pElemChild = pElemRoot->FirstChildElement();
	TiXmlAttribute *pAttrChild = NULL;
	
	while(true)
	{
		if(pElemChild == NULL)
		{
			break;
		}
		
		if(pElemChild->Type() != TiXmlNode::TINYXML_ELEMENT)
		{
			continue;
		}
		
		pAttrChild = pElemChild->FirstAttribute();
		
		if(EmSz::Equal( pElemChild->Attribute( szKeyName), szKeyValue))
		{
			EmMapStr::const_iterator iterMap;
			for(iterMap = rMapStr.begin(); iterMap != rMapStr.end(); iterMap++)
			{
				pElemChild->SetAttribute(iterMap->first , iterMap->second);
			}
			bUpdated = true;
			break;
		}
		
		pElemChild = pElemChild->NextSiblingElement();
	}

	m_bUpdated = bUpdated;
	return iResult;
}
Example #17
0
void searchXMLData(TiXmlElement* pElem)  
{  
	TiXmlHandle hRoot(0);  
	TiXmlElement* pSubElem = pElem;  
	TiXmlAttribute* pAttrib = NULL;  


	//Set current node to root node and determine childe node is exist or not  
	hRoot = TiXmlHandle(pSubElem);  
	pSubElem = hRoot.FirstChildElement().Element();  
	if (!pSubElem) return;  

	char* pszNode = NULL;  
	char* pszAttrib = NULL;  
	char* pszText = NULL;  

	while (pSubElem)  
	{  
		//node  
		pszNode = (char*)pSubElem->Value();  
		if (pszNode)  
		printf("Node: %s\n", pszNode);  

		//Attribute  
		pAttrib = pSubElem->FirstAttribute();  
		while (pAttrib)  
		{  
			char* pszAttrib = (char*)pAttrib->Name();  
			char* pszText = (char*)pAttrib->Value();  

			printf("------------Attribute: %s, Data: %s\n", pszAttrib, pszText);  

			pAttrib = pAttrib->Next();  
		}  

		//Data  
		pszText = (char*)pSubElem->GetText();  
		if (pszText)  
		printf("Text: %s\n", pszText);  

		// Recursive call for searching child node based current node  
		searchXMLData(pSubElem);  
		pSubElem = pSubElem->NextSiblingElement();  
	}  
}  
void ProjectConfiguration::XmlWrite(TiXmlElement* Node,cbProject* Project)
{
    TiXmlElement* LibFinder = Node->FirstChildElement("lib_finder");
    if ( !LibFinder ) LibFinder = Node->InsertEndChild(TiXmlElement("lib_finder"))->ToElement();

    LibFinder->Clear();

    if ( m_DisableAuto )
    {
        LibFinder->SetAttribute("disable_auto","1");
    }

    for ( size_t i=0; i<m_GlobalUsedLibs.Count(); i++ )
    {
        LibFinder->InsertEndChild(TiXmlElement("lib"))->ToElement()->SetAttribute("name",cbU2C(m_GlobalUsedLibs[i]));
    }

    for ( wxMultiStringMap::iterator i=m_TargetsUsedLibs.begin();
            i!=m_TargetsUsedLibs.end();
            ++i )
    {
        if ( !Project->GetBuildTarget(i->first) ) continue;

        wxArrayString& Libs = i->second;
        if ( Libs.Count() )
        {
            TiXmlElement* TargetElem = LibFinder->InsertEndChild(TiXmlElement("target"))->ToElement();
            TargetElem->SetAttribute("name",cbU2C(i->first));
            for ( size_t i=0; i<Libs.Count(); i++ )
            {
                TargetElem->InsertEndChild(TiXmlElement("lib"))->ToElement()->SetAttribute("name",cbU2C(Libs[i]));
            }
        }
    }

    if ( !LibFinder->FirstAttribute() && !LibFinder->FirstChild() )
    {
        // LibFinder is empty, let's delete it so it doesn't trash here
        Node->RemoveChild(LibFinder);
    }
}
Example #19
0
std::string em::EmXml::ReadRootChildAttr( const char* szKeyName, const char* szKeyValue, const char* szAttrName )
{
	std::string strResult;
	int iResult = 0;

	TiXmlElement *pElemRoot = m_pDoc->RootElement();
	if(pElemRoot == NULL)
	{
		return "";
	}
	
	TiXmlElement *pElemChild = pElemRoot->FirstChildElement();
	TiXmlAttribute *pAttrChild = NULL;
	
	while(true)
	{
		if(pElemChild == NULL)
		{
			break;
		}
		
		if(pElemChild->Type() != TiXmlNode::TINYXML_ELEMENT)
		{
			continue;
		}
		
		pAttrChild = pElemChild->FirstAttribute();
		
		if( EmSz::Equal(pElemChild->Attribute( szKeyName ), szKeyValue) )
		{
			strResult = pElemChild->Attribute( szAttrName);
			break;
		}
		
		pElemChild = pElemChild->NextSiblingElement();
	}
	return strResult;
}
Example #20
0
bool WalkingSpeed::LoadJPSfireInfo(const std::string & projectFilename )
{
   boost::filesystem::path p(projectFilename);
   std::string projectRootDir = p.parent_path().string();

     TiXmlDocument doc(projectFilename);
   if (!doc.LoadFile()) {
        Log->Write("ERROR: \t%s", doc.ErrorDesc());
        Log->Write("ERROR: \t could not parse the project file");
        return false;
   }

   TiXmlNode* JPSfireNode = doc.RootElement()->FirstChild("JPSfire");
   if( ! JPSfireNode ) {
        Log->Write("INFO:\tcould not find any JPSfire information");
        return true;
   }

   TiXmlElement* JPSfireCompElem = JPSfireNode->FirstChildElement("B_walking_speed");
   if(JPSfireCompElem) {
       if(JPSfireCompElem->FirstAttribute()){
           std::string study = xmltoa(JPSfireCompElem->Attribute("study"), "");
           std::string irritant = xmltoa(JPSfireCompElem->Attribute("irritant"), "");
           std::string extinction_grids = xmltoa(JPSfireCompElem->Attribute("extinction_grids"), "");
           std::string filepath = projectRootDir + "/" + extinction_grids; //TODO: check compatibility
           if (projectRootDir.empty()  ) // directory is "."
                filepath =  extinction_grids;

           double updateIntervall = xmltof(JPSfireCompElem->Attribute("update_time"), 0.);
           double finalTime = xmltof(JPSfireCompElem->Attribute("final_time"), 0.);
           Log->Write("INFO:\tJPSfire Module B_walking_speed: \n \tstudy: %s \n\tdata: %s \n\tupdate time: %.1f s | final time: %.1f s | irritant: %s",
                      study.c_str(), filepath.c_str(), updateIntervall, finalTime, irritant.c_str());
           _FMStorage = std::make_shared<FDSMeshStorage>(filepath, finalTime, updateIntervall, study, irritant);
           return true;
       }
   }
   return false;
}
Example #21
0
// -----------------------------------------------------------------------------
// Obtain the name of the current element's first attribute
// -----------------------------------------------------------------------------
const char* SimXMLDocument::firstAttribute()
{
   // Get the current element
   if(m_paNode.empty())
   {
      return StringTable->EmptyString;
   }
   const int iLastElement = m_paNode.size() - 1;
   TiXmlElement* pNode = m_paNode[iLastElement];
   if(!pNode)
   {
      return StringTable->EmptyString;
   }

   // Gets its first attribute, if any
   m_CurrentAttribute = pNode->FirstAttribute();
   if(!m_CurrentAttribute)
   {
      return StringTable->EmptyString;
   }

   return m_CurrentAttribute->Name();
}
Example #22
0
int em::EmXml::ReadRootAttrMap( EmMapStr &rMapStr )
{
	int iResult = 0;
	rMapStr.clear();

	TiXmlElement *pElemRoot = m_pDoc->RootElement();
	if(pElemRoot == NULL)
	{
		return 0;
	}
	TiXmlAttribute *pAttr = pElemRoot->FirstAttribute();
	while(true)
	{
		if(pAttr == NULL)
		{
			break;
		}
		rMapStr[  pAttr->Name() ] =  pAttr->Value() ;
		pAttr = pAttr->Next();
	}
	iResult = rMapStr.size();
	return iResult;
}
Example #23
0
// static member function
HeeksObj* CWaterline::ReadFromXMLElement(TiXmlElement* element)
{
	CWaterline* new_object = new CWaterline;

	std::list<TiXmlElement *> elements_to_remove;

	// read solid ids
	for(TiXmlElement* pElem = heeksCAD->FirstXMLChildElement( element ) ; pElem; pElem = pElem->NextSiblingElement())
	{
		std::string name(pElem->Value());
		if(name == "params"){
			new_object->m_params.ReadFromXMLElement(pElem);
			elements_to_remove.push_back(pElem);
		}
		else if(name == "solid"){
			for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
			{
				std::string name(a->Name());
				if(name == "id"){
					int id = a->IntValue();
					new_object->m_solids.push_back(id);
				}
			}
			elements_to_remove.push_back(pElem);
		}
	}

	for (std::list<TiXmlElement*>::iterator itElem = elements_to_remove.begin(); itElem != elements_to_remove.end(); itElem++)
	{
		heeksCAD->RemoveXMLChild( element, *itElem);
	}

	new_object->ReadBaseXML(element);

	return new_object;
}
Example #24
0
                 break;

             case 4: // we have 4 bits, and keep 1
                 vchRet.push_back((left<<4) | (dec>>1));
                 left = dec & 1;
                 mode = 5;
                 break;

             case 5: // we have 1 bit, and keep 6
                 left = left << 5 | dec;
                 mode = 6;
                 break;

             case 6: // we have 6 bits, and keep 3
                 vchRet.push_back((left<<2) | (dec>>3));
                 left = dec & 7;
                 mode = 7;
                 break;

             case 7: // we have 3 bits, and keep 0
                 vchRet.push_back((left<<5) | dec);
                 mode = 0;
                 break;
         }
    }

    if (pfInvalid)
        switch (mode)
        {
            case 0: // 8n base32 characters processed: ok
                break;

            case 1: // 8n+1 base32 characters processed: impossible
            case 3: //   +3
            case 6: //   +6
                *pfInvalid = true;
                break;

            case 2: // 8n+2 base32 characters processed: require '======'
                if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
                    *pfInvalid = true;
                break;

            case 4: // 8n+4 base32 characters processed: require '===='
                if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
                    *pfInvalid = true;
                break;

            case 5: // 8n+5 base32 characters processed: require '==='
                if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
                    *pfInvalid = true;
                break;

            case 7: // 8n+7 base32 characters processed: require '='
                if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
                    *pfInvalid = true;
                break;
        }

    return vchRet;
}

string DecodeBase32(const string& str)
{
    vector<unsigned char> vchRet = DecodeBase32(str.c_str());
    return string((const char*)&vchRet[0], vchRet.size());
}


bool WildcardMatch(const char* psz, const char* mask)
{
    loop
    {
        switch (*mask)
        {
        case '\0':
            return (*psz == '\0');
        case '*':
            return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
        case '?':
            if (*psz == '\0')
                return false;
            break;
        default:
            if (*psz != *mask)
                return false;
            break;
        }
        psz++;
        mask++;
    }
}

bool WildcardMatch(const string& str, const string& mask)
{
    return WildcardMatch(str.c_str(), mask.c_str());
}








static std::string FormatException(std::exception* pex, const char* pszThread)
{
#ifdef WIN32
    char pszModule[MAX_PATH] = "";
    GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
#else
    const char* pszModule = "hqcoin";
#endif
    if (pex)
        return strprintf(
            "EXCEPTION: %s       \n%s       \n%s in %s       \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
    else
        return strprintf(
            "UNKNOWN EXCEPTION       \n%s in %s       \n", pszModule, pszThread);
}

void LogException(std::exception* pex, const char* pszThread)
{
    std::string message = FormatException(pex, pszThread);
    printf("\n%s", message.c_str());
}

void PrintException(std::exception* pex, const char* pszThread)
{
    std::string message = FormatException(pex, pszThread);
    printf("\n\n************************\n%s\n", message.c_str());
    fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
    strMiscWarning = message;
    throw;
}

void PrintExceptionContinue(std::exception* pex, const char* pszThread)
{
    std::string message = FormatException(pex, pszThread);
    printf("\n\n************************\n%s\n", message.c_str());
    fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
    strMiscWarning = message;
}

boost::filesystem::path GetDefaultDataDir()
{
    namespace fs = boost::filesystem;
    // Windows < Vista: C:\Documents and Settings\Username\Application Data\HQCoin
    // Windows >= Vista: C:\Users\Username\AppData\Roaming\HQCoin
    // Mac: ~/Library/Application Support/HQCoin
    // Unix: ~/.hqcoin
#ifdef WIN32
    // Windows
    return GetSpecialFolderPath(CSIDL_APPDATA) / "HQCoin";
#else
    fs::path pathRet;
    char* pszHome = getenv("HOME");
    if (pszHome == NULL || strlen(pszHome) == 0)
        pathRet = fs::path("/");
    else
        pathRet = fs::path(pszHome);
#ifdef MAC_OSX
    // Mac
    pathRet /= "Library/Application Support";
Example #25
0
bool CGmObjShapeStaticItem::ReadXML( TiXmlNode* poParent, unsigned int uiCounter )
{
	if( !poParent )
		return false;
	
	static char acTxt_[256];
	if( uiCounter == 0 )
	{
	}
	
	switch ( poParent->Type() )
	{
	case TiXmlNode::DOCUMENT:
		LOG( "XML: Document" );
	break;
	case TiXmlNode::ELEMENT:
	{
		const char *pcName = poParent->Value();
		//LOG( "name: %s\n", pcName );
		if( !strcmp( pcName, "item" ) )
		{
			LOG( "item:\n" );
			
			TiXmlElement * poElement = poParent->ToElement();
			if( poElement )
			{
				TiXmlAttribute* poAttrib = poElement->FirstAttribute();
				while( poAttrib )
				{
					const char *pcName = poAttrib->Name();
					if( !strcmp( pcName, "name" ) )
					{
						STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
						LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
						m_oName = acTxt_;
					}
					if( !strcmp( pcName, "type" ) )
					{
						STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
						LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
						if( !strcmp( acTxt_, "weapon" ) )
							m_eType = TYPE_WEAPON;
						else if( !strcmp( acTxt_, "energy" ) )
							m_eType = TYPE_ENERGY;
						else if( !strcmp( acTxt_, "ammo" ) )
							m_eType = TYPE_AMMO;
						else if( !strcmp( acTxt_, "key" ) )
							m_eType = TYPE_KEY;
						else
							m_eType = TYPE_UNDEFINED;
					}
					if( !strcmp( pcName, "cycle_duration" ) )
					{
						double dVal;
						if( poAttrib->QueryDoubleValue( &dVal ) == TIXML_SUCCESS )
						{
							LOG( "%s: %f\n", poAttrib->Name(), float( dVal ) );
							if( dVal >= 0.0 )
								m_iTickDurCycle = int( dVal / m_dTInteractionInterval_ );
							else
								m_iTickDurCycle = -1;
						}
					}
					if( !strcmp( pcName, "rotation_y_speed" ) )
					{
						double dVal;
						if( poAttrib->QueryDoubleValue( &dVal ) == TIXML_SUCCESS )
						{
							LOG( "%s: %f\n", poAttrib->Name(), float( dVal ) );
							m_fRotationYSpeed = float( dVal * 360.0 );
						}
					}
					if( !strcmp( pcName, "weapon_name" )
					 && ( m_eType == TYPE_WEAPON || m_eType == TYPE_AMMO ) )
					{
						STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
						LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
						m_oWeaponName = acTxt_;
					}
					if( !strcmp( pcName, "energy" ) && m_eType == TYPE_ENERGY )
					{
						double dVal;
						if( poAttrib->QueryDoubleValue( &dVal ) == TIXML_SUCCESS )
						{
							LOG( "%s: %f\n", poAttrib->Name(), float( dVal ) );
							m_fEnergy = float( dVal );
						}
					}
					if( !strcmp( pcName, "ammo" )
					 && ( m_eType == TYPE_WEAPON || m_eType == TYPE_AMMO ) )
					{
						int iVal;
						if( poAttrib->QueryIntValue( &iVal ) == TIXML_SUCCESS
						 && iVal > 0 )
						{
							LOG( "%s: %d\n", poAttrib->Name(), iVal );
							m_uiAmmo = iVal;
						}
					}
					if( !strcmp( pcName, "key" ) && m_eType == TYPE_ENERGY )
					{
						int iVal;
						if( poAttrib->QueryIntValue( &iVal ) == TIXML_SUCCESS
						 && iVal > 0 )
						{
							LOG( "%s: %d\n", poAttrib->Name(), iVal );
							m_uiKey = iVal;
						}
					}
					poAttrib = poAttrib->Next();
				}
			}
		}
		if( !strcmp( pcName, "animation" ) )
		{
			LOG( "animation:\n" );
			
			TiXmlElement * poElement = poParent->ToElement();
			if( poElement )
			{
				TiXmlAttribute* poAttrib = poElement->FirstAttribute();
				while( poAttrib )
				{
					const char *pcName = poAttrib->Name();
					if( !strcmp( pcName, "file_name" ) )
					{
						STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
						LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
						m_poAnim = m_poResMan_->NewAnim3( CStr( "item/" ) + acTxt_ );
					}
					poAttrib = poAttrib->Next();
				}
			}
		}
		// Gleich wie in GmObjShapeDynamicEnemy.cpp.
		if( !strcmp( pcName, "mesh" ) )
		{
			LOG( "mesh:\n" );

			CStr oFileName, oSubDir;

			TiXmlElement * poElement = poParent->ToElement();
			if( poElement )
			{
				TiXmlAttribute* poAttrib = poElement->FirstAttribute();
				while( poAttrib )
				{
					const char *pcName = poAttrib->Name();
					if( !strcmp( pcName, "sub_dir" ) )
					{
						STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
						LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
						oSubDir = acTxt_;
					}
					else if( !strcmp( pcName, "file_name" ) )
					{
						STRING_COPY( acTxt_, sizeof(acTxt_), poAttrib->Value() );
						LOG( "%s: %s\n", poAttrib->Name(), acTxt_ );
						oFileName = acTxt_;
					}
					poAttrib = poAttrib->Next();
				}
			}
			if( oFileName.GetSize() )
			{
				CGMesh * poMesh( m_poResMan_->NewMeshObj( oSubDir, oFileName ) ); //, false, false ) );
				if( poMesh )
				{
					m_oLstMesh.Append( poMesh );
				}
			}
		}
	}
	break;
	case TiXmlNode::COMMENT:
		//LOG( "XML: Comment: [%s]", poParent->Value());
	break;
	case TiXmlNode::UNKNOWN:
		//LOG( "XML: Unknown" );
	break;
	case TiXmlNode::TEXT:
		//LOG( "XML: Text: [%s]", poParent->ToText()->Value() );
	break;
	case TiXmlNode::DECLARATION:
		//LOG( "XML: Declaration" );
	break;
	default:
	break;
	}
	LOG( "\n" );

	++uiCounter;

	for( TiXmlNode* poChild = poParent->FirstChild(); poChild != 0; poChild = poChild->NextSibling() )
	{
		ReadXML( poChild, uiCounter );
	}
	
	// Ganz am Schluss...
	if( uiCounter == 1 )
	{
	}
	return true;
}
TMaterialPaths LoadMaterialFile(char* szMaterialPath)
{
	TMaterialPaths tPaths;
	memset(&tPaths, 0, sizeof(TMaterialPaths));
	
	//////////////////////////////////////////////////////////////////////////
	// Defaults
	//////////////////////////////////////////////////////////////////////////
	tPaths.bError				= false;
	tPaths.eShaderFlags			= eShaderFlag_none;
	tPaths.iGeometryTopology	= D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
	tPaths.eDiffuseShaderFlags  = eHydTex_PS;
	tPaths.eSpecularShaderFlags = eHydTex_PS;
	tPaths.eBumpShaderFlags		 = eHydTex_PS;
	
	TiXmlDocument doc(szMaterialPath);
	doc.LoadFile();
	if(doc.Error())
	{
		tPaths.bError = true;
		return tPaths;
	}

	TiXmlElement* pRoot = doc.RootElement();
	TiXmlNode* pChild;
	for( pChild = pRoot->FirstChild(); pChild; pChild = pChild->NextSibling() )
	{
		TiXmlElement* pElement = pChild->ToElement();
		if(!pElement)
			continue;

		const char* pValue = pElement->Value();
		if(strcmp(pValue, "parameters") == 0)
		{
		
			for( TiXmlNode* pParameter = pElement->FirstChild(); pParameter; pParameter = pParameter->NextSibling() )
			{
				TiXmlElement* pChildElement = pParameter->ToElement();
				if(!pChildElement)
					continue;

				TiXmlAttribute* idAttribute = pChildElement->FirstAttribute();
				if(!idAttribute || !idAttribute->Value())
					continue;

				if(strcmp(idAttribute->Value(), "txDiffuse") == 0)
				{
					tPaths.bDiffuse = true;
					TiXmlNode* pNode = pChildElement->FirstChild();
					if(pNode)
					{
						strcpy_s(tPaths.szTexturePath, 256, pNode->Value());

						const char* szShaderFlags = pChildElement->Attribute("shader_flags");
						if(szShaderFlags)
						{
							int iShaderFlags = atoi(szShaderFlags);
							int iCurrentFlags = (int)tPaths.eDiffuseShaderFlags;
							iCurrentFlags |= iShaderFlags;
							tPaths.eDiffuseShaderFlags = (EHydTex_ShaderFlags)iCurrentFlags;
						}

					}
					continue;

				}

				if(strcmp(idAttribute->Value(), "txSpec") == 0)
				{
					tPaths.bSpecular = true;
					TiXmlNode* pNode = pChildElement->FirstChild();
					if(pNode)
					{
						strcpy_s(tPaths.szSpecularPath, 256, pNode->Value());

						const char* szShaderFlags = pChildElement->Attribute("shader_flags");
						if(szShaderFlags)
						{
							int iShaderFlags = atoi(szShaderFlags);
							int iCurrentFlags = (int)tPaths.eSpecularShaderFlags;
							iCurrentFlags |= iShaderFlags;
							tPaths.eSpecularShaderFlags = (EHydTex_ShaderFlags)iCurrentFlags;
						}
					}
					continue;

				}

				if(strcmp(idAttribute->Value(), "txNormal") == 0)
				{
					TiXmlNode* pNode = pChildElement->FirstChild();
					if(pNode)
					{
						strcpy_s(tPaths.szNormalPath, 256, pNode->Value());

						const char* szShaderFlags = pChildElement->Attribute("shader_flags");
						if(szShaderFlags)
						{
							int iShaderFlags = atoi(szShaderFlags);
							int iCurrentFlags = (int)tPaths.eBumpShaderFlags;
							iCurrentFlags |= iShaderFlags;
							tPaths.eBumpShaderFlags = (EHydTex_ShaderFlags)iCurrentFlags;
						}
					}
					continue;

				}
			}
			}
			

		

		if(strcmp(pValue, "shader") == 0)
		{
			TiXmlNode* pNode = pElement->FirstChild();
			if(pNode)
				strcpy_s(tPaths.szShaderPath, 256, pNode->Value());

			// - Check for shader flags and topology attributes
			const char* szShaderFlags = pElement->Attribute("shader_flags");
			if(szShaderFlags)
				tPaths.eShaderFlags = (HydShader_EShaderFlags)atoi(szShaderFlags);

			const char* szTopology = pElement->Attribute("topology");
			if(szTopology)
				tPaths.iGeometryTopology = (D3D_PRIMITIVE_TOPOLOGY)atoi(szTopology);

			continue;
		}
	}
	return tPaths;
}
Example #27
0
HRESULT CSafeSaverNetImpl::CopyCfData(SCfData& sCfData)
{
    CCameraData* pCameraData = sCfData.pRefData->GetItem();
    DWORD32 dwDataLen = 0;
    memcpy((char*)m_sBuf.addr + dwDataLen, &pCameraData->header, sizeof(pCameraData->header));
    dwDataLen += sizeof(pCameraData->header);
    memcpy((char*)m_sBuf.addr + dwDataLen, pCameraData->pbInfo, pCameraData->header.dwInfoSize);
    dwDataLen += pCameraData->header.dwInfoSize;
    memcpy((char*)m_sBuf.addr + dwDataLen, pCameraData->pbData, pCameraData->header.dwDataSize);
    dwDataLen += pCameraData->header.dwDataSize;

    if (0 == sCfData.iDataType)//识别结果,修正CarID
    {
        BLOCK_HEADER cBlockHeader;
        char* pXML = NULL;
        char* pbTemp = (char*)m_sBuf.addr + sizeof(CAMERA_INFO_HEADER);
        //修正数据类型
        DWORD32 dwRecordType = CAMERA_RECORD_HISTORY;
        memcpy(pbTemp+8, &dwRecordType, 4);

        for (int i = 0; i < (int)pCameraData->header.dwInfoSize; )
        {
            memcpy(&cBlockHeader, pbTemp, sizeof(BLOCK_HEADER));
            pbTemp += sizeof(BLOCK_HEADER);
            i += sizeof(BLOCK_HEADER);

            if (cBlockHeader.dwID == BLOCK_XML_TYPE)  // 识别结果XML附加信息
            {
                pXML = pbTemp;
                if (strstr(pXML, "违章:是"))
                {
                    sCfData.dwDataInfo = 1;
                }
                break;
            }

            pbTemp += cBlockHeader.dwLen;
            i += cBlockHeader.dwLen;
        }

        TiXmlDocument xmlDoc;
        xmlDoc.Parse(pXML);
        if (pXML && xmlDoc.RootElement())
        {
            TiXmlElement* pElement = xmlDoc.RootElement()->FirstChildElement("ResultSet");
            if (pElement)
            {
                pElement = pElement->FirstChildElement("Result");
            }
            TiXmlElement* pElementCarId = NULL;
            TiXmlElement* pElementTimeLow = NULL;
            TiXmlElement* pElementTimeHigh = NULL;
            if (pElement)
            {
                pElementCarId = pElement->FirstChildElement("CarID");
                pElementTimeLow = pElement->FirstChildElement("TimeLow");
                pElementTimeHigh = pElement->FirstChildElement("TimeHigh");
            }
            if (pElementTimeLow)
            {
                const TiXmlAttribute* attr = pElementTimeLow->FirstAttribute();
                for (; attr; attr=attr->Next())
                {
                    if (0 == strcmp(attr->Name(), "value"))
                    {
                        sscanf(attr->Value(), "%u", &sCfData.dwTimeLow);
                        break;
                    }
                }
            }
            if (pElementTimeHigh)
            {
                const TiXmlAttribute* attr = pElementTimeHigh->FirstAttribute();
                for (; attr; attr=attr->Next())
                {
                    if (0 == strcmp(attr->Name(), "value"))
                    {
                        sscanf(attr->Value(), "%u", &sCfData.dwTimeHigh);
                        break;
                    }
                }
            }
            if (pElementCarId)
            {
#if FIX_FILE_VER == 1
                DWORD32 dwCarID = m_cCfRecord.GetHourCount(sCfData.dwTimeLow, sCfData.dwTimeHigh);
#else
                DWORD32 dwCarID;
                GetHourCount(sCfData.dwTimeLow, sCfData.dwTimeHigh, &dwCarID);
                sCfData.dwIndex = dwCarID;
#endif
                char szValue[32] = {0};
                sprintf(szValue, "%u", dwCarID);
                pElementCarId->SetAttribute("value", szValue);

                TiXmlPrinter cTxPr;
                xmlDoc.Accept(&cTxPr);
                strcpy(pXML, cTxPr.CStr());
            }
        }
    }
    else
    {
        REAL_TIME_STRUCT rtsTime;
        ConvertMsToTime(sCfData.dwTimeLow, sCfData.dwTimeHigh, &rtsTime);
        sCfData.dwIndex = rtsTime.wMinute * 60 + rtsTime.wSecond;
    }

    return S_OK;
}
Example #28
0
int main()
{

    //
    // We start with the 'demoStart' todo list. Process it. And
    // should hopefully end up with the todo list as illustrated.
    //
    const char* demoStart =
        "<?xml version=\"1.0\"  standalone='no' >\n"
        "<!-- Our to do list data -->"
        "<ToDo>\n"
        "<!-- Do I need a secure PDA? -->\n"
        "<Item priority=\"1\" distance='close'> Go to the <bold>Toy store!</bold></Item>"
        "<Item priority=\"2\" distance='none'> Do bills   </Item>"
        "<Item priority=\"2\" distance='far &amp; back'> Look for Evil Dinosaurs! </Item>"
        "</ToDo>";

    {

#ifdef TIXML_USE_STL
        //	What the todo list should look like after processing.
        // In stream (no formatting) representation.
        const char* demoEnd =
            "<?xml version=\"1.0\" standalone=\"no\" ?>"
            "<!-- Our to do list data -->"
            "<ToDo>"
            "<!-- Do I need a secure PDA? -->"
            "<Item priority=\"2\" distance=\"close\">Go to the"
            "<bold>Toy store!"
            "</bold>"
            "</Item>"
            "<Item priority=\"1\" distance=\"far\">Talk to:"
            "<Meeting where=\"School\">"
            "<Attendee name=\"Marple\" position=\"teacher\" />"
            "<Attendee name=\"Voel\" position=\"counselor\" />"
            "</Meeting>"
            "<Meeting where=\"Lunch\" />"
            "</Item>"
            "<Item priority=\"2\" distance=\"here\">Do bills"
            "</Item>"
            "</ToDo>";
#endif

        // The example parses from the character string (above):
#if defined( WIN32 ) && defined( TUNE )
        _CrtMemCheckpoint( &startMemState );
#endif

        {
            // Write to a file and read it back, to check file I/O.

            TiXmlDocument doc( "demotest.xml" );
            doc.Parse( demoStart );

            if ( doc.Error() )
            {
                printf( "Error in %s: %s\n", doc.Value(), doc.ErrorDesc() );
                exit( 1 );
            }
            doc.SaveFile();
        }

        TiXmlDocument doc( "demotest.xml" );
        bool loadOkay = doc.LoadFile();

        if ( !loadOkay )
        {
            printf( "Could not load test file 'demotest.xml'. Error='%s'. Exiting.\n", doc.ErrorDesc() );
            exit( 1 );
        }

        printf( "** Demo doc read from disk: ** \n\n" );
        printf( "** Printing via doc.Print **\n" );
        doc.Print( stdout );

        {
            printf( "** Printing via TiXmlPrinter **\n" );
            TiXmlPrinter printer;
            doc.Accept( &printer );
            fprintf( stdout, "%s", printer.CStr() );
        }
#ifdef TIXML_USE_STL
        {
            printf( "** Printing via operator<< **\n" );
            std::cout << doc;
        }
#endif
        TiXmlNode* node = 0;
        TiXmlElement* todoElement = 0;
        TiXmlElement* itemElement = 0;


        // --------------------------------------------------------
        // An example of changing existing attributes, and removing
        // an element from the document.
        // --------------------------------------------------------

        // Get the "ToDo" element.
        // It is a child of the document, and can be selected by name.
        node = doc.FirstChild( "ToDo" );
        assert( node );
        todoElement = node->ToElement();
        assert( todoElement  );

        // Going to the toy store is now our second priority...
        // So set the "priority" attribute of the first item in the list.
        node = todoElement->FirstChildElement();	// This skips the "PDA" comment.
        assert( node );
        itemElement = node->ToElement();
        assert( itemElement  );
        itemElement->SetAttribute( "priority", 2 );

        // Change the distance to "doing bills" from
        // "none" to "here". It's the next sibling element.
        itemElement = itemElement->NextSiblingElement();
        assert( itemElement );
        itemElement->SetAttribute( "distance", "here" );

        // Remove the "Look for Evil Dinosaurs!" item.
        // It is 1 more sibling away. We ask the parent to remove
        // a particular child.
        itemElement = itemElement->NextSiblingElement();
        todoElement->RemoveChild( itemElement );

        itemElement = 0;

        // --------------------------------------------------------
        // What follows is an example of created elements and text
        // nodes and adding them to the document.
        // --------------------------------------------------------

        // Add some meetings.
        TiXmlElement item( "Item" );
        item.SetAttribute( "priority", "1" );
        item.SetAttribute( "distance", "far" );

        TiXmlText text( "Talk to:" );

        TiXmlElement meeting1( "Meeting" );
        meeting1.SetAttribute( "where", "School" );

        TiXmlElement meeting2( "Meeting" );
        meeting2.SetAttribute( "where", "Lunch" );

        TiXmlElement attendee1( "Attendee" );
        attendee1.SetAttribute( "name", "Marple" );
        attendee1.SetAttribute( "position", "teacher" );

        TiXmlElement attendee2( "Attendee" );
        attendee2.SetAttribute( "name", "Voel" );
        attendee2.SetAttribute( "position", "counselor" );

        // Assemble the nodes we've created:
        meeting1.InsertEndChild( attendee1 );
        meeting1.InsertEndChild( attendee2 );

        item.InsertEndChild( text );
        item.InsertEndChild( meeting1 );
        item.InsertEndChild( meeting2 );

        // And add the node to the existing list after the first child.
        node = todoElement->FirstChild( "Item" );
        assert( node );
        itemElement = node->ToElement();
        assert( itemElement );

        todoElement->InsertAfterChild( itemElement, item );

        printf( "\n** Demo doc processed: ** \n\n" );
        doc.Print( stdout );


#ifdef TIXML_USE_STL
        printf( "** Demo doc processed to stream: ** \n\n" );
        cout << doc << endl << endl;
#endif

        // --------------------------------------------------------
        // Different tests...do we have what we expect?
        // --------------------------------------------------------

        int count = 0;
        TiXmlElement*	element;

        //////////////////////////////////////////////////////

#ifdef TIXML_USE_STL
        cout << "** Basic structure. **\n";
        ostringstream outputStream( ostringstream::out );
        outputStream << doc;
        XmlTest( "Output stream correct.",	string( demoEnd ).c_str(),
                 outputStream.str().c_str(), true );
#endif

        node = doc.RootElement();
        assert( node );
        XmlTest( "Root element exists.", true, ( node != 0 && node->ToElement() ) );
        XmlTest ( "Root element value is 'ToDo'.", "ToDo",  node->Value());

        node = node->FirstChild();
        XmlTest( "First child exists & is a comment.", true, ( node != 0 && node->ToComment() ) );
        node = node->NextSibling();
        XmlTest( "Sibling element exists & is an element.", true, ( node != 0 && node->ToElement() ) );
        XmlTest ( "Value is 'Item'.", "Item", node->Value() );

        node = node->FirstChild();
        XmlTest ( "First child exists.", true, ( node != 0 && node->ToText() ) );
        XmlTest ( "Value is 'Go to the'.", "Go to the", node->Value() );


        //////////////////////////////////////////////////////
        printf ("\n** Iterators. **\n");

        // Walk all the top level nodes of the document.
        count = 0;
        for( node = doc.FirstChild();
                node;
                node = node->NextSibling() )
        {
            count++;
        }
        XmlTest( "Top level nodes, using First / Next.", 3, count );

        count = 0;
        for( node = doc.LastChild();
                node;
                node = node->PreviousSibling() )
        {
            count++;
        }
        XmlTest( "Top level nodes, using Last / Previous.", 3, count );

        // Walk all the top level nodes of the document,
        // using a different syntax.
        count = 0;
        for( node = doc.IterateChildren( 0 );
                node;
                node = doc.IterateChildren( node ) )
        {
            count++;
        }
        XmlTest( "Top level nodes, using IterateChildren.", 3, count );

        // Walk all the elements in a node.
        count = 0;
        for( element = todoElement->FirstChildElement();
                element;
                element = element->NextSiblingElement() )
        {
            count++;
        }
        XmlTest( "Children of the 'ToDo' element, using First / Next.",
                 3, count );

        // Walk all the elements in a node by value.
        count = 0;
        for( node = todoElement->FirstChild( "Item" );
                node;
                node = node->NextSibling( "Item" ) )
        {
            count++;
        }
        XmlTest( "'Item' children of the 'ToDo' element, using First/Next.", 3, count );

        count = 0;
        for( node = todoElement->LastChild( "Item" );
                node;
                node = node->PreviousSibling( "Item" ) )
        {
            count++;
        }
        XmlTest( "'Item' children of the 'ToDo' element, using Last/Previous.", 3, count );

#ifdef TIXML_USE_STL
        {
            cout << "\n** Parsing. **\n";
            istringstream parse0( "<Element0 attribute0='foo0' attribute1= noquotes attribute2 = '&gt;' />" );
            TiXmlElement element0( "default" );
            parse0 >> element0;

            XmlTest ( "Element parsed, value is 'Element0'.", "Element0", element0.Value() );
            XmlTest ( "Reads attribute 'attribute0=\"foo0\"'.", "foo0", element0.Attribute( "attribute0" ));
            XmlTest ( "Reads incorrectly formatted 'attribute1=noquotes'.", "noquotes", element0.Attribute( "attribute1" ) );
            XmlTest ( "Read attribute with entity value '>'.", ">", element0.Attribute( "attribute2" ) );
        }
#endif

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

            TiXmlDocument docTest;
            docTest.Parse( error );
            XmlTest( "Error row", docTest.ErrorRow(), 3 );
            XmlTest( "Error column", docTest.ErrorCol(), 17 );
            //printf( "error=%d id='%s' row %d col%d\n", (int) doc.Error(), doc.ErrorDesc(), doc.ErrorRow()+1, doc.ErrorCol() + 1 );

        }

#ifdef TIXML_USE_STL
        {
            //////////////////////////////////////////////////////
            cout << "\n** Streaming. **\n";

            // Round trip check: stream in, then stream back out to verify. The stream
            // out has already been checked, above. We use the output

            istringstream inputStringStream( outputStream.str() );
            TiXmlDocument document0;

            inputStringStream >> document0;

            ostringstream outputStream0( ostringstream::out );
            outputStream0 << document0;

            XmlTest( "Stream round trip correct.",	string( demoEnd ).c_str(),
                     outputStream0.str().c_str(), true );

            std::string str;
            str << document0;

            XmlTest( "String printing correct.", string( demoEnd ).c_str(),
                     str.c_str(), true );
        }
#endif
    }

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

        TiXmlDocument doc;
        doc.Parse( str );

        TiXmlElement* ele = doc.FirstChildElement();

        int iVal, result;
        double dVal;

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

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

        TiXmlDocument doc;
        doc.Parse( str );

        TiXmlElement* ele = doc.FirstChildElement();

        int iVal;
        double dVal;

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

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

        XmlTest( "Attribute round trip. c-string.", "strValue", cStr );
        XmlTest( "Attribute round trip. int.", 1, iVal );
        XmlTest( "Attribute round trip. double.", -1, (int)dVal );
    }

    {
        const char* str =	"\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n"
                            "</room>";

        TiXmlDocument doc;
        doc.SetTabSize( 8 );
        doc.Parse( str );

        TiXmlHandle docHandle( &doc );
        TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" );

        assert( docHandle.Node() );
        assert( roomHandle.Element() );

        TiXmlElement* room = roomHandle.Element();
        assert( room );
        TiXmlAttribute* doors = room->FirstAttribute();
        assert( doors );

        XmlTest( "Location tracking: Tab 8: room row", room->Row(), 1 );
        XmlTest( "Location tracking: Tab 8: room col", room->Column(), 49 );
        XmlTest( "Location tracking: Tab 8: doors row", doors->Row(), 1 );
        XmlTest( "Location tracking: Tab 8: doors col", doors->Column(), 55 );
    }

    {
        const char* str =	"\t<?xml version=\"1.0\" standalone=\"no\" ?>\t<room doors='2'>\n"
                            "  <!-- Silly example -->\n"
                            "    <door wall='north'>A great door!</door>\n"
                            "\t<door wall='east'/>"
                            "</room>";

        TiXmlDocument doc;
        doc.Parse( str );

        TiXmlHandle docHandle( &doc );
        TiXmlHandle roomHandle = docHandle.FirstChildElement( "room" );
        TiXmlHandle commentHandle = docHandle.FirstChildElement( "room" ).FirstChild();
        TiXmlHandle textHandle = docHandle.FirstChildElement( "room" ).ChildElement( "door", 0 ).FirstChild();
        TiXmlHandle door0Handle = docHandle.FirstChildElement( "room" ).ChildElement( 0 );
        TiXmlHandle door1Handle = docHandle.FirstChildElement( "room" ).ChildElement( 1 );

        assert( docHandle.Node() );
        assert( roomHandle.Element() );
        assert( commentHandle.Node() );
        assert( textHandle.Text() );
        assert( door0Handle.Element() );
        assert( door1Handle.Element() );

        TiXmlDeclaration* declaration = doc.FirstChild()->ToDeclaration();
        assert( declaration );
        TiXmlElement* room = roomHandle.Element();
        assert( room );
        TiXmlAttribute* doors = room->FirstAttribute();
        assert( doors );
        TiXmlText* text = textHandle.Text();
        TiXmlComment* comment = commentHandle.Node()->ToComment();
        assert( comment );
        TiXmlElement* door0 = door0Handle.Element();
        TiXmlElement* door1 = door1Handle.Element();

        XmlTest( "Location tracking: Declaration row", declaration->Row(), 1 );
        XmlTest( "Location tracking: Declaration col", declaration->Column(), 5 );
        XmlTest( "Location tracking: room row", room->Row(), 1 );
        XmlTest( "Location tracking: room col", room->Column(), 45 );
        XmlTest( "Location tracking: doors row", doors->Row(), 1 );
        XmlTest( "Location tracking: doors col", doors->Column(), 51 );
        XmlTest( "Location tracking: Comment row", comment->Row(), 2 );
        XmlTest( "Location tracking: Comment col", comment->Column(), 3 );
        XmlTest( "Location tracking: text row", text->Row(), 3 );
        XmlTest( "Location tracking: text col", text->Column(), 24 );
        XmlTest( "Location tracking: door0 row", door0->Row(), 3 );
        XmlTest( "Location tracking: door0 col", door0->Column(), 5 );
        XmlTest( "Location tracking: door1 row", door1->Row(), 4 );
        XmlTest( "Location tracking: door1 col", door1->Column(), 5 );
    }


    // --------------------------------------------------------
    // UTF-8 testing. It is important to test:
    //	1. Making sure name, value, and text read correctly
    //	2. Row, Col functionality
    //	3. Correct output
    // --------------------------------------------------------
    printf ("\n** UTF-8 **\n");
    {
        TiXmlDocument doc( "utf8test.xml" );
        doc.LoadFile();
        if ( doc.Error() && doc.ErrorId() == TiXmlBase::TIXML_ERROR_OPENING_FILE ) {
            printf( "WARNING: File 'utf8test.xml' not found.\n"
                    "(Are you running the test from the wrong directory?)\n"
                    "Could not test UTF-8 functionality.\n" );
        }
        else
        {
            TiXmlHandle docH( &doc );
            // Get the attribute "value" from the "Russian" element and check it.
            TiXmlElement* element = docH.FirstChildElement( "document" ).FirstChildElement( "Russian" ).Element();
            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" ), true );
            XmlTest( "UTF-8: Russian value row.", 4, element->Row() );
            XmlTest( "UTF-8: Russian value column.", 5, element->Column() );

            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>";

            TiXmlText* text = docH.FirstChildElement( "document" ).FirstChildElement( (const char*) russianElementName ).Child( 0 ).Text();
            XmlTest( "UTF-8: Browsing russian element name.",
                     russianText,
                     text->Value(),
                     true );
            XmlTest( "UTF-8: Russian element name row.", 7, text->Row() );
            XmlTest( "UTF-8: Russian element name column.", 47, text->Column() );

            TiXmlDeclaration* dec = docH.Child( 0 ).Node()->ToDeclaration();
            XmlTest( "UTF-8: Declaration column.", 1, dec->Column() );
            XmlTest( "UTF-8: Document column.", 1, doc.Column() );

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

            // Check the round trip.
            char savedBuf[256];
            char verifyBuf[256];
            int okay = 1;

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

            //bool firstLineBOM=true;
            if ( saved && verify )
            {
                while ( fgets( verifyBuf, 256, verify ) )
                {
                    fgets( savedBuf, 256, saved );
                    NullLineEndings( verifyBuf );
                    NullLineEndings( savedBuf );

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

            // On most Western machines, this is an element that contains
            // the word "resume" with the correct accents, in a latin encoding.
            // It will be something else completely on non-wester machines,
            // which is why TinyXml is switching to UTF-8.
            const char latin[] = "<element>r\x82sum\x82</element>";

            TiXmlDocument latinDoc;
            latinDoc.Parse( latin, 0, TIXML_ENCODING_LEGACY );

            text = latinDoc.FirstChildElement()->FirstChild()->ToText();
            XmlTest( "Legacy encoding: Verify text element.", "r\x82sum\x82", text->Value() );
        }
    }

    //////////////////////
    // Copy and assignment
    //////////////////////
    printf ("\n** Copy and Assignment **\n");
    {
        TiXmlElement element( "foo" );
        element.Parse( "<element name='value' />", 0, TIXML_ENCODING_UNKNOWN );

        TiXmlElement elementCopy( element );
        TiXmlElement elementAssign( "foo" );
        elementAssign.Parse( "<incorrect foo='bar'/>", 0, TIXML_ENCODING_UNKNOWN );
        elementAssign = element;

        XmlTest( "Copy/Assign: element copy #1.", "element", elementCopy.Value() );
        XmlTest( "Copy/Assign: element copy #2.", "value", elementCopy.Attribute( "name" ) );
        XmlTest( "Copy/Assign: element assign #1.", "element", elementAssign.Value() );
        XmlTest( "Copy/Assign: element assign #2.", "value", elementAssign.Attribute( "name" ) );
        XmlTest( "Copy/Assign: element assign #3.", true, ( 0 == elementAssign.Attribute( "foo" )) );

        TiXmlComment comment;
        comment.Parse( "<!--comment-->", 0, TIXML_ENCODING_UNKNOWN );
        TiXmlComment commentCopy( comment );
        TiXmlComment commentAssign;
        commentAssign = commentCopy;
        XmlTest( "Copy/Assign: comment copy.", "comment", commentCopy.Value() );
        XmlTest( "Copy/Assign: comment assign.", "comment", commentAssign.Value() );

        TiXmlUnknown unknown;
        unknown.Parse( "<[unknown]>", 0, TIXML_ENCODING_UNKNOWN );
        TiXmlUnknown unknownCopy( unknown );
        TiXmlUnknown unknownAssign;
        unknownAssign.Parse( "incorrect", 0, TIXML_ENCODING_UNKNOWN );
        unknownAssign = unknownCopy;
        XmlTest( "Copy/Assign: unknown copy.", "[unknown]", unknownCopy.Value() );
        XmlTest( "Copy/Assign: unknown assign.", "[unknown]", unknownAssign.Value() );

        TiXmlText text( "TextNode" );
        TiXmlText textCopy( text );
        TiXmlText textAssign( "incorrect" );
        textAssign = text;
        XmlTest( "Copy/Assign: text copy.", "TextNode", textCopy.Value() );
        XmlTest( "Copy/Assign: text assign.", "TextNode", textAssign.Value() );

        TiXmlDeclaration dec;
        dec.Parse( "<?xml version='1.0' encoding='UTF-8'?>", 0, TIXML_ENCODING_UNKNOWN );
        TiXmlDeclaration decCopy( dec );
        TiXmlDeclaration decAssign;
        decAssign = dec;

        XmlTest( "Copy/Assign: declaration copy.", "UTF-8", decCopy.Encoding() );
        XmlTest( "Copy/Assign: text assign.", "UTF-8", decAssign.Encoding() );

        TiXmlDocument doc;
        elementCopy.InsertEndChild( textCopy );
        doc.InsertEndChild( decAssign );
        doc.InsertEndChild( elementCopy );
        doc.InsertEndChild( unknownAssign );

        TiXmlDocument docCopy( doc );
        TiXmlDocument docAssign;
        docAssign = docCopy;

#ifdef TIXML_USE_STL
        std::string original, copy, assign;
        original << doc;
        copy << docCopy;
        assign << docAssign;
        XmlTest( "Copy/Assign: document copy.", original.c_str(), copy.c_str(), true );
        XmlTest( "Copy/Assign: document assign.", original.c_str(), assign.c_str(), true );

#endif
    }

    //////////////////////////////////////////////////////
#ifdef TIXML_USE_STL
    printf ("\n** Parsing, no Condense Whitespace **\n");
    TiXmlBase::SetCondenseWhiteSpace( false );
    {
        istringstream parse1( "<start>This  is    \ntext</start>" );
        TiXmlElement text1( "text" );
        parse1 >> text1;

        XmlTest ( "Condense white space OFF.", "This  is    \ntext",
                  text1.FirstChild()->Value(),
                  true );
    }
    TiXmlBase::SetCondenseWhiteSpace( true );
#endif

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

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

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

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

        str = "<foo>This is <b>text</b></foo>";
        doc.Clear();
        TiXmlBase::SetCondenseWhiteSpace( false );
        doc.Parse( str );
        TiXmlBase::SetCondenseWhiteSpace( true );
        element = doc.RootElement();

        XmlTest( "GetText() partial.", "This is ", element->GetText() );
    }


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

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

#ifdef TIXML_USE_STL
        //cout << doc << '\n';

        doc.Clear();

        istringstream parse0( str );
        parse0 >> doc;
        //cout << doc << '\n';

        XmlTest( "CDATA stream.", doc.FirstChildElement()->FirstChild()->Value(),
                 "I am > the rules!\n...since I make symbolic puns",
                 true );
#endif

        TiXmlDocument doc1 = doc;
        //doc.Print();

        XmlTest( "CDATA copy.", doc1.FirstChildElement()->FirstChild()->Value(),
                 "I am > the rules!\n...since I make symbolic puns",
                 true );
    }
    {
        // [ 1482728 ] Wrong wide char parsing
        char buf[256];
        buf[255] = 0;
        for( int i=0; i<255; ++i ) {
            buf[i] = (char)((i>=32) ? i : 32);
        }
        TIXML_STRING str( "<xmlElement><![CDATA[" );
        str += buf;
        str += "]]></xmlElement>";

        TiXmlDocument doc;
        doc.Parse( str.c_str() );

        TiXmlPrinter printer;
        printer.SetStreamPrinting();
        doc.Accept( &printer );

        XmlTest( "CDATA with all bytes #1.", str.c_str(), printer.CStr(), true );

#ifdef TIXML_USE_STL
        doc.Clear();
        istringstream iss( printer.Str() );
        iss >> doc;
        std::string out;
        out << doc;
        XmlTest( "CDATA with all bytes #2.", out.c_str(), printer.CStr(), true );
#endif
    }
    {
        // [ 1480107 ] Bug-fix for STL-streaming of CDATA that contains tags
        // CDATA streaming had a couple of bugs, that this tests for.
        const char* str =	"<xmlElement>"
                            "<![CDATA["
                            "<b>I am > the rules!</b>\n"
                            "...since I make symbolic puns"
                            "]]>"
                            "</xmlElement>";
        TiXmlDocument doc;
        doc.Parse( str );
        doc.Print();

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

#ifdef TIXML_USE_STL

        doc.Clear();

        istringstream parse0( str );
        parse0 >> doc;

        XmlTest( "CDATA stream. [ 1480107 ]", doc.FirstChildElement()->FirstChild()->Value(),
                 "<b>I am > the rules!</b>\n...since I make symbolic puns",
                 true );
#endif

        TiXmlDocument doc1 = doc;
        //doc.Print();

        XmlTest( "CDATA copy. [ 1480107 ]", doc1.FirstChildElement()->FirstChild()->Value(),
                 "<b>I am > the rules!</b>\n...since I make symbolic puns",
                 true );
    }
    //////////////////////////////////////////////////////
    // Visit()



    //////////////////////////////////////////////////////
    printf( "\n** Fuzzing... **\n" );

    const int FUZZ_ITERATION = 300;

    // The only goal is not to crash on bad input.
    int len = (int) strlen( demoStart );
    for( int i=0; i<FUZZ_ITERATION; ++i )
    {
        char* demoCopy = new char[ len+1 ];
        strcpy( demoCopy, demoStart );

        demoCopy[ i%len ] = (char)((i+1)*3);
        demoCopy[ (i*7)%len ] = '>';
        demoCopy[ (i*11)%len ] = '<';

        TiXmlDocument xml;
        xml.Parse( demoCopy );

        delete [] demoCopy;
    }
    printf( "** Fuzzing Complete. **\n" );

    //////////////////////////////////////////////////////
    printf ("\n** Bug regression tests **\n");

    // InsertBeforeChild and InsertAfterChild causes crash.
    {
        TiXmlElement parent( "Parent" );
        TiXmlElement childText0( "childText0" );
        TiXmlElement childText1( "childText1" );
        TiXmlNode* childNode0 = parent.InsertEndChild( childText0 );
        TiXmlNode* childNode1 = parent.InsertBeforeChild( childNode0, childText1 );

        XmlTest( "Test InsertBeforeChild on empty node.", ( childNode1 == parent.FirstChild() ), true );
    }

    {
        // InsertBeforeChild and InsertAfterChild causes crash.
        TiXmlElement parent( "Parent" );
        TiXmlElement childText0( "childText0" );
        TiXmlElement childText1( "childText1" );
        TiXmlNode* childNode0 = parent.InsertEndChild( childText0 );
        TiXmlNode* childNode1 = parent.InsertAfterChild( childNode0, childText1 );

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

    // Reports of missing constructors, irregular string problems.
    {
        // Missing constructor implementation. No test -- just compiles.
        TiXmlText text( "Missing" );

#ifdef TIXML_USE_STL
        // Missing implementation:
        TiXmlDocument doc;
        string name = "missing";
        doc.LoadFile( name );

        TiXmlText textSTL( name );
#else
        // verifying some basic string functions:
        TiXmlString a;
        TiXmlString b( "Hello" );
        TiXmlString c( "ooga" );

        c = " World!";
        a = b;
        a += c;
        a = a;

        XmlTest( "Basic TiXmlString test. ", "Hello World!", a.c_str() );
#endif
    }

    // Long filenames crashing STL version
    {
        TiXmlDocument doc( "midsummerNightsDreamWithAVeryLongFilenameToConfuseTheStringHandlingRoutines.xml" );
        bool loadOkay = doc.LoadFile();
        loadOkay = true;	// get rid of compiler warning.
        // Won't pass on non-dev systems. Just a "no crash" check.
        //XmlTest( "Long filename. ", true, loadOkay );
    }

    {
        // 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>";

        TiXmlDocument doc( "passages.xml" );
        doc.Parse( passages );
        TiXmlElement* 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( "textfile.txt", "w" );
        if ( textfile )
        {
            psg->Print( textfile, 0 );
            fclose( textfile );
        }
        textfile = fopen( "textfile.txt", "r" );
        assert( 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.' />",
                     buf,
                     true );
        }
        fclose( textfile );
    }

    {
        FILE* textfile = fopen( "test5.xml", "w" );
        if ( textfile )
        {
            fputs("<?xml version='1.0'?><a.elem xmi.version='2.0'/>", textfile);
            fclose(textfile);

            TiXmlDocument doc;
            doc.LoadFile( "test5.xml" );
            XmlTest( "dot in element attributes and names", doc.Error(), 0);
        }
    }

    {
        FILE* textfile = fopen( "test6.xml", "w" );
        if ( textfile )
        {
            fputs("<element><Name>1.1 Start easy ignore fin thickness&#xA;</Name></element>", textfile );
            fclose(textfile);

            TiXmlDocument doc;
            bool result = doc.LoadFile( "test6.xml" );
            XmlTest( "Entity with one digit.", result, true );

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

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

        TiXmlDocument doc;
        doc.Parse( doctype );
        doc.SaveFile( "test7.xml" );
        doc.Clear();
        doc.LoadFile( "test7.xml" );

        TiXmlHandle docH( &doc );
        TiXmlUnknown* unknown = docH.Child( 1 ).Unknown();
        XmlTest( "Correct value of unknown.", "!DOCTYPE PLAY SYSTEM 'play.dtd'", unknown->Value() );
#ifdef TIXML_USE_STL
        TiXmlNode* node = docH.Child( 2 ).Node();
        std::string str;
        str << (*node);
        XmlTest( "Correct streaming of unknown.", "<!ELEMENT title (#PCDATA)>", str.c_str() );
#endif
    }

    {
        // [ 791411 ] Formatting bug
        // Comments do not stream out correctly.
        const char* doctype =
            "<!-- Somewhat<evil> -->";
        TiXmlDocument doc;
        doc.Parse( doctype );

        TiXmlHandle docH( &doc );
        TiXmlComment* comment = docH.Child( 0 ).Node()->ToComment();

        XmlTest( "Comment formatting.", " Somewhat<evil> ", comment->Value() );
#ifdef TIXML_USE_STL
        std::string str;
        str << (*comment);
        XmlTest( "Comment streaming.", "<!-- Somewhat<evil> -->", str.c_str() );
#endif
    }

    {
        // [ 870502 ] White space issues
        TiXmlDocument doc;
        TiXmlText* text;
        TiXmlHandle docH( &doc );

        const char* doctype0 = "<element> This has leading and trailing space </element>";
        const char* doctype1 = "<element>This has  internal space</element>";
        const char* doctype2 = "<element> This has leading, trailing, and  internal space </element>";

        TiXmlBase::SetCondenseWhiteSpace( false );
        doc.Clear();
        doc.Parse( doctype0 );
        text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
        XmlTest( "White space kept.", " This has leading and trailing space ", text->Value() );

        doc.Clear();
        doc.Parse( doctype1 );
        text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
        XmlTest( "White space kept.", "This has  internal space", text->Value() );

        doc.Clear();
        doc.Parse( doctype2 );
        text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
        XmlTest( "White space kept.", " This has leading, trailing, and  internal space ", text->Value() );

        TiXmlBase::SetCondenseWhiteSpace( true );
        doc.Clear();
        doc.Parse( doctype0 );
        text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
        XmlTest( "White space condensed.", "This has leading and trailing space", text->Value() );

        doc.Clear();
        doc.Parse( doctype1 );
        text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
        XmlTest( "White space condensed.", "This has internal space", text->Value() );

        doc.Clear();
        doc.Parse( doctype2 );
        text = docH.FirstChildElement( "element" ).Child( 0 ).Text();
        XmlTest( "White space condensed.", "This has leading, trailing, and internal space", text->Value() );
    }

    {
        // Double attributes
        const char* doctype = "<element attr='red' attr='blue' />";

        TiXmlDocument doc;
        doc.Parse( doctype );

        XmlTest( "Parsing repeated attributes.", true, doc.Error() );	// is an  error to tinyxml (didn't use to be, but caused issues)
        //XmlTest( "Parsing repeated attributes.", "blue", doc.FirstChildElement( "element" )->Attribute( "attr" ) );
    }

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

        TiXmlDocument doc;
        doc.Parse( doctype );
        XmlTest( "Embedded null throws error.", true, doc.Error() );

#ifdef TIXML_USE_STL
        istringstream strm( doctype );
        doc.Clear();
        doc.ClearError();
        strm >> doc;
        XmlTest( "Embedded null throws error.", true, doc.Error() );
#endif
    }

    {
        // Legacy mode test. (This test may only pass on a western system)
        const char* str =
            "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"
            "<ä>"
            "CöntäntßäöüÄÖÜ"
            "</ä>";

        TiXmlDocument doc;
        doc.Parse( str );

        TiXmlHandle docHandle( &doc );
        TiXmlHandle aHandle = docHandle.FirstChildElement( "ä" );
        TiXmlHandle tHandle = aHandle.Child( 0 );
        assert( aHandle.Element() );
        assert( tHandle.Text() );
        XmlTest( "ISO-8859-1 Parsing.", "CöntäntßäöüÄÖÜ", tHandle.Text()->Value() );
    }

    {
        // Empty documents should return TIXML_ERROR_PARSING_EMPTY, bug 1070717
        const char* str = "    ";
        TiXmlDocument doc;
        doc.Parse( str );
        XmlTest( "Empty document error TIXML_ERROR_DOCUMENT_EMPTY", TiXmlBase::TIXML_ERROR_DOCUMENT_EMPTY, doc.ErrorId() );
    }
#ifndef TIXML_USE_STL
    {
        // String equality. [ 1006409 ] string operator==/!= no worky in all cases
        TiXmlString temp;
        XmlTest( "Empty tinyxml string compare equal", ( temp == "" ), true );

        TiXmlString    foo;
        TiXmlString    bar( "" );
        XmlTest( "Empty tinyxml string compare equal", ( foo == bar ), true );
    }

#endif
    {
        // Bug [ 1195696 ] from marlonism
        TiXmlBase::SetCondenseWhiteSpace(false);
        TiXmlDocument xml;
        xml.Parse("<text><break/>This hangs</text>");
        XmlTest( "Test safe error return.", xml.Error(), false );
    }

    {
        // Bug [ 1243992 ] - another infinite loop
        TiXmlDocument doc;
        doc.SetCondenseWhiteSpace(false);
        doc.Parse("<p><pb></pb>test</p>");
    }
    {
        // Low entities
        TiXmlDocument xml;
        xml.Parse( "<test>&#x0e;</test>" );
        const char result[] = { 0x0e, 0 };
        XmlTest( "Low entities.", xml.FirstChildElement()->GetText(), result );
        xml.Print();
    }
    {
        // Bug [ 1451649 ] Attribute values with trailing quotes not handled correctly
        TiXmlDocument xml;
        xml.Parse( "<foo attribute=bar\" />" );
        XmlTest( "Throw error with bad end quotes.", xml.Error(), true );
    }
#ifdef TIXML_USE_STL
    {
        // Bug [ 1449463 ] Consider generic query
        TiXmlDocument xml;
        xml.Parse( "<foo bar='3' barStr='a string'/>" );

        TiXmlElement* ele = xml.FirstChildElement();
        double d;
        int i;
        float f;
        bool b;
        std::string str;

        XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &d ), TIXML_SUCCESS );
        XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &i ), TIXML_SUCCESS );
        XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &f ), TIXML_SUCCESS );
        XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "bar", &b ), TIXML_WRONG_TYPE );
        XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "nobar", &b ), TIXML_NO_ATTRIBUTE );
        XmlTest( "QueryValueAttribute", ele->QueryValueAttribute( "barStr", &str ), TIXML_SUCCESS );

        XmlTest( "QueryValueAttribute", (d==3.0), true );
        XmlTest( "QueryValueAttribute", (i==3), true );
        XmlTest( "QueryValueAttribute", (f==3.0f), true );
        XmlTest( "QueryValueAttribute", (str==std::string( "a string" )), true );
    }
#endif

#ifdef TIXML_USE_STL
    {
        // [ 1505267 ] redundant malloc in TiXmlElement::Attribute
        TiXmlDocument xml;
        xml.Parse( "<foo bar='3' />" );
        TiXmlElement* ele = xml.FirstChildElement();
        double d;
        int i;

        std::string bar = "bar";

        const std::string* atrrib = ele->Attribute( bar );
        ele->Attribute( bar, &d );
        ele->Attribute( bar, &i );

        XmlTest( "Attribute", atrrib->empty(), false );
        XmlTest( "Attribute", (d==3.0), true );
        XmlTest( "Attribute", (i==3), true );
    }
#endif

    {
        // [ 1356059 ] Allow TiXMLDocument to only be at the top level
        TiXmlDocument xml, xml2;
        xml.InsertEndChild( xml2 );
        XmlTest( "Document only at top level.", xml.Error(), true );
        XmlTest( "Document only at top level.", xml.ErrorId(), TiXmlBase::TIXML_ERROR_DOCUMENT_TOP_ONLY );
    }

    {
        // [ 1663758 ] Failure to report error on bad XML
        TiXmlDocument 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);
    }

    {
        // [ 1635701 ] fail to parse files with a tag separated into two lines
        // I'm not sure this is a bug. Marked 'pending' for feedback.
        TiXmlDocument xml;
        xml.Parse( "<title><p>text</p\n><title>" );
        //xml.Print();
        //XmlTest( "Tag split by newline", xml.Error(), false );
    }

#ifdef TIXML_USE_STL
    {
        // [ 1475201 ] TinyXML parses entities in comments
        TiXmlDocument xml;
        istringstream parse1( "<!-- declarations for <head> & <body> -->"
                              "<!-- far &amp; away -->" );
        parse1 >> xml;

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

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

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

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

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

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

        TiXmlNode* ele = 0;
        while ( (ele = xml.FirstChildElement( "Parent" )->IterateChildren( ele ) ) != 0 ) {
            ++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;

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


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

    {
        // This one must not result in an infinite loop
        TiXmlDocument xml;
        xml.Parse( "<infinite>loop" );
        XmlTest( "Infinite loop test.", true, true );
    }

    {
        // 1709904 - can not repro the crash
        {
            TiXmlDocument xml;
            xml.Parse( "<tag>/</tag>" );
            XmlTest( "Odd XML parsing.", xml.FirstChild()->Value(), "tag" );
        }
        /* Could not repro. {
        	TiXmlDocument xml;
        	xml.LoadFile( "EQUI_Inventory.xml" );
        	//XmlTest( "Odd XML parsing.", xml.FirstChildElement()->Value(), "XML" );
        	TiXmlPrinter printer;
        	xml.Accept( &printer );
        	fprintf( stdout, "%s", printer.CStr() );
        }*/
    }

    /*  1417717 experiment
    {
    	TiXmlDocument xml;
    	xml.Parse("<text>Dan & Tracie</text>");
    	xml.Print(stdout);
    }
    {
    	TiXmlDocument xml;
    	xml.Parse("<text>Dan &foo; Tracie</text>");
    	xml.Print(stdout);
    }
    */

#if defined( WIN32 ) && defined( TUNE )
    _CrtMemCheckpoint( &endMemState );
    //_CrtMemDumpStatistics( &endMemState );

    _CrtMemState diffMemState;
    _CrtMemDifference( &diffMemState, &startMemState, &endMemState );
    _CrtMemDumpStatistics( &diffMemState );
#endif

    printf ("\nPass %d, Fail %d\n", gPass, gFail);
    return gFail;
}
Example #29
0
TiXmlNode * readXMLConfig::selectChildNode(TiXmlNode * pNode,string nodeName,string nodeAttrName,string nodeAttrValue)  
{  
    if(pNode == NULL)  
    {  
        return NULL;  
    }  
    TiXmlNode * pSelectedNode = NULL;  
    TiXmlNode * pChildNode = NULL;  
    int t = pNode->Type();  
    switch (t)  
    {  
    case TiXmlText::TINYXML_DOCUMENT:  
    case TiXmlText::TINYXML_DECLARATION:  
    case TiXmlText::TINYXML_TEXT:  
    case TiXmlText::TINYXML_UNKNOWN:  
    case TiXmlText::TINYXML_COMMENT:  
        break;  
    case TiXmlText::TINYXML_ELEMENT:  
    if(pNode->Value() == nodeName)  
    {  
        //cout << pNode->Value() << endl;  
        if(!nodeAttrName.empty() && !nodeAttrValue.empty())  
        {  
            TiXmlElement * pElement = pNode->ToElement();  

            TiXmlAttribute * pAttr = pElement->FirstAttribute();  
            TiXmlAttribute * pNextAttr =NULL;  
            if(pAttr != NULL)  
            {    
                do  
                {                            
                    if(pAttr->Name()==nodeAttrName&&pAttr->Value()== nodeAttrValue)  
                    {  
                        //cout << pAttr->Value() << endl;  
                        return pNode;  
                    }  
                }while(pAttr = pAttr->Next());  
            }  
        }  
        else  
        {  
            return pNode;  
        }  
             
    }  
    else  
    {  
        //循环访问它的每一个元素  
        for(pChildNode=pNode->FirstChild();  
            pChildNode!=0;  
            pChildNode = pChildNode->NextSibling())  
        {  
            pSelectedNode = selectChildNode(  
                                pChildNode,  
                                nodeName,  
                                nodeAttrName,  
                                nodeAttrValue);  
            if(pSelectedNode)  
            {  
                return pSelectedNode;  
            }  
        }  
    }  
 
    default:break;  
    }  
    return NULL;  
}
Example #30
0
/**
	createResolutionData
	Create Android resolution file as follow imported resolution file
*/
int CreateResolutionData(RESOLUTION* resolutionResult, int index, TiXmlElement* pSubElement, char* directory) {
	/** Get node */
	TiXmlHandle hRoot(0);
	TiXmlElement* pElement = pSubElement;
	TiXmlAttribute* pAttribute = NULL;

	/** Set current dept node to root node */
	hRoot = TiXmlHandle(pElement);
	/** Check has child root */
	pElement = hRoot.FirstChildElement().Element();

	/** Set xml properties and root node for save file */
	TiXmlDocument docArray[RESOLUTION_TYPE_COUNT];
	TiXmlDeclaration* dec[RESOLUTION_TYPE_COUNT] = { ENCODING, ENCODING, ENCODING, ENCODING };
	for (int i = 0; i < RESOLUTION_TYPE_COUNT; i++) {
		docArray[i].LinkEndChild(dec[i]);
	}

	/** Add root node */
	TiXmlElement* pRoot[RESOLUTION_TYPE_COUNT] = { FIRST_NODE, FIRST_NODE, FIRST_NODE, FIRST_NODE };
	for (int i = 0; i < RESOLUTION_TYPE_COUNT; i++) {
		docArray[i].LinkEndChild(pRoot[i]);
	}

	/** Add child node */
	TiXmlElement* pElementArray[RESOLUTION_TYPE_COUNT];

	/** If has child */
	if (pElement) {
		char* pszNode = NULL;			/** For save node */
		char* pszAttributeValue = NULL;	/** For save attribute's name (key) */
		char* pszAttributeName = NULL;	/** for save attribute's name (value) */

		/** Repeat if has child node */
		while (pElement) {
			/** Get node */
			pszNode = (char*)pElement->Value();

			/** Get attribute */
			pAttribute = pElement->FirstAttribute();

			/** If has attribute */
			while (pAttribute) {
				pszAttributeValue = (char*)pAttribute->Name();
				pszAttributeName = (char*)pAttribute->Value();
				pAttribute = pAttribute->Next();
			}

			/** Get resoultion unit info */
			char* pszText = (char*)pElement->GetText();

			/** Calculete resolution size */
			struct RESOLUTION result;
			result = ConvertResolution(pszAttributeName, strtod(pszText, NULL), RESOLUTION_HDPI); //It's HDPI type unconditionally in prototype
			resolutionResult[index++] = result;
			double resolution_value[RESOLUTION_TYPE_COUNT] = { result.ldpi, result.mdpi, result.hdpi, result.xhdpi };

			char temp[100];
			for (int i = 0; i < RESOLUTION_TYPE_COUNT; i++) {
				/** For create new resolution file */
				sprintf_s(temp, sizeof(temp), "%.2lfdp", resolution_value[i]);
				pElementArray[i] = new TiXmlElement("dimen");
				pElementArray[i]->LinkEndChild(new TiXmlText(temp));
				pRoot[i]->LinkEndChild(pElementArray[i]);
				pElementArray[i]->SetAttribute("name", pszAttributeName);
			}

			/** Call self recursively for search child node of current node */
			CreateResolutionData(resolutionResult, index, pElement, NULL);
			pElement = pElement->NextSiblingElement();
		}
	}

	/** Save file */
	if (directory != NULL) {
		char savepath[RESOLUTION_TYPE_COUNT][100] = { "_ldpi.xml", "_mdpi.xml",  "_hdpi.xml", "_xhdpi.xml" };

		for (int i = 0; i < RESOLUTION_TYPE_COUNT; i++) {
			char filepath[100] = "";

			strncpy_s(filepath, directory, sizeof(filepath));
			strcat_s(filepath, sizeof(filepath), savepath[i]);
			docArray[i].SaveFile(filepath);
		}

		AfxMessageBox(_T("Save successfully!"));
	}

	return index;
}