コード例 #1
0
ファイル: tinyxml.cpp プロジェクト: zhouxs1023/Editor
void TiXmlElement::Print( FILE* cfile, int depth ) const
{
	int i;
	assert( cfile );
	for ( i=0; i<depth; i++ ) {
		fprintf( cfile, "    " );
	}

	fprintf( cfile, "<%s", value.c_str() );

	const TiXmlAttribute* attrib;
	for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() )
	{
		fprintf( cfile, " " );
		attrib->Print( cfile, depth );
	}

	// There are 3 different formatting approaches:
	// 1) An element without children is printed as a <foo /> node
	// 2) An element with only a text child is printed as <foo> text </foo>
	// 3) An element with children is printed on multiple lines.
	TiXmlNode* node;
	if ( !firstChild )
	{
		fprintf( cfile, " />" );
	}
	else if ( firstChild == lastChild && firstChild->ToText() )
	{
		fprintf( cfile, ">" );
		firstChild->Print( cfile, depth + 1 );
		fprintf( cfile, "</%s>", value.c_str() );
	}
	else
	{
		fprintf( cfile, ">" );

		for ( node = firstChild; node; node=node->NextSibling() )
		{
			if ( !node->ToText() )
			{
				fprintf( cfile, "\n" );
			}
			node->Print( cfile, depth+1 );
		}
		fprintf( cfile, "\n" );
		for( i=0; i<depth; ++i ) {
			fprintf( cfile, "    " );
		}
		fprintf( cfile, "</%s>", value.c_str() );
	}
}
コード例 #2
0
ファイル: xmlfunctions.cpp プロジェクト: Typz/FileZilla
wxString GetTextElement(TiXmlElement* node, const char* name)
{
	wxASSERT(node);

	TiXmlElement* element = node->FirstChildElement(name);
	if (!element)
		return wxString();

	TiXmlNode* textNode = element->FirstChild();
	if (!textNode || !textNode->ToText())
		return wxString();

	return ConvLocal(textNode->Value());
}
コード例 #3
0
wxString GetTextElement(TiXmlElement* node)
{
	wxASSERT(node);

	for (TiXmlNode* pChild = node->FirstChild(); pChild; pChild = pChild->NextSibling())
	{
		if (!pChild->ToText())
			continue;

		return ConvLocal(pChild->Value());
	}

	return _T("");
}
コード例 #4
0
void CKSXML_Read_Project::Set_Temp_Online_Project_Name(TiXmlNode* pParent)
{
	if ( !pParent ) return;
	
	TiXmlNode* pChild = pParent->FirstChild();
	
	if ( pChild ){
		TiXmlText* pText;
		pText = pChild->ToText();
		
		msTemp_Online_Project_Name =  pText->Value();
	}
	
}
コード例 #5
0
ファイル: TINYXML_xmlIO.cpp プロジェクト: cndesantana/epicell
void XMLreader::mainProcessorIni( std::vector<TiXmlNode*> pParentVect )
{
    std::map<int, TiXmlNode*> parents;
    for (unsigned iParent=0; iParent<pParentVect.size(); ++iParent) {
        EPC_ASSERT( pParentVect[iParent]->Type()==TiXmlNode::DOCUMENT ||
                          pParentVect[iParent]->Type()==TiXmlNode::ELEMENT );

        TiXmlElement* pParentElement = pParentVect[iParent]->ToElement();
        int id=0;
        if (pParentElement) {
            const char* attribute = pParentElement->Attribute("id");
            if (attribute) {
                std::stringstream attributestr(attribute);
                attributestr >> id;
            }
        }
        parents[id] = pParentVect[iParent];
    }

    std::map<int, TiXmlNode*>::iterator it = parents.begin();
    name = it->second->ValueStr();

    for (; it != parents.end(); ++it) {
        int id = it->first;

        TiXmlNode* pParent = it->second;
        Data& data = data_map[id];
        data.text="";

        typedef std::map<std::string, std::vector<TiXmlNode*> > ChildMap;
        ChildMap childMap;
        TiXmlNode* pChild;
        for ( pChild = pParent->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) 
        {
            int type = pChild->Type();
            if ( type==TiXmlNode::ELEMENT ) {
                std::string name(pChild->Value());
                childMap[name].push_back(pChild);
            }
            else if ( type==TiXmlNode::TEXT ) {
                data.text = pChild->ToText()->ValueStr();
            }
        }
        for (ChildMap::iterator it = childMap.begin(); it != childMap.end(); ++it) {
            std::vector<TiXmlNode*> pChildVect = it->second;
            data.children.push_back( new XMLreader( pChildVect ) );
        }
    }
}
コード例 #6
0
ファイル: LevelParser.cpp プロジェクト: rrodrig6/BoardGame
void LevelParser::parseTileLayer( TiXmlElement* pTileElement, std::vector<Layer*> *pLayers, const std::vector<Tileset> *pTilesets )
{
	TileLayer* pTileLayer = new TileLayer( m_tileSize, *pTilesets );

	// tile data
	std::vector< std::vector<int> > data;

	std::string decodedIDs;
	TiXmlElement* pDataNode;

	for( TiXmlElement* e = pTileElement->FirstChildElement(); e !=NULL; e = e->NextSiblingElement() )
	{
		if( e->Value() == std::string("data") )
		{
			pDataNode = e;
		}
	}

	for( TiXmlNode* e = pDataNode->FirstChild(); e != NULL; e = e->NextSibling() )
	{
		TiXmlText* text = e->ToText();
		std::string t = text->Value();
		decodedIDs = base64_decode(t);
	}

	// uncompress zlib compression
	uLongf numGids = m_width * m_height * sizeof( int );
	std::vector< unsigned > gids( m_width * m_height );
	uncompress( (Bytef*) &gids[0], &numGids, (const Bytef* ) decodedIDs.c_str(), decodedIDs.size() );

	std::vector< int > layerRow( m_width );
	
	for( int j = 0; j < m_height; j++ )
	{
		data.push_back( layerRow );
	}

	for( int rows = 0; rows < m_height; rows++ )
	{
		for( int cols = 0; cols < m_width; cols++ )
		{
			data[rows][cols] = gids[rows * m_width + cols];
		}
	}

	pTileLayer->setTileIDs( data );
	
	pLayers->push_back( pTileLayer );
}
コード例 #7
0
ファイル: Options.cpp プロジェクト: ErichKrause/filezilla
bool COptions::GetXmlValue(unsigned int nID, wxString &value, TiXmlElement *settings /*=0*/)
{
	if (!settings)
	{
		if (!m_pXmlFile)
			return false;

		settings = m_pXmlFile->GetElement()->FirstChildElement("Settings");
		if (!settings)
		{
			TiXmlNode *node = m_pXmlFile->GetElement()->InsertEndChild(TiXmlElement("Settings"));
			if (!node)
				return false;
			settings = node->ToElement();
			if (!settings)
				return false;
		}
	}

	TiXmlNode *node = 0;
	while ((node = settings->IterateChildren("Setting", node)))
	{
		TiXmlElement *setting = node->ToElement();
		if (!setting)
			continue;

		const char *attribute = setting->Attribute("name");
		if (!attribute)
			continue;
		if (strcmp(attribute, options[nID].name))
			continue;

		TiXmlNode *text = setting->FirstChild();
		if (!text)
		{
			value.clear();
			return true;
		}

		if (!text->ToText())
			return false;

		value = ConvLocal(text->Value());

		return true;
	}

	return false;
}
コード例 #8
0
void CKSXML_Read_Project::Read_Branch_Object(TiXmlElement* pElement)
{
	if ( !pElement ) return ;
	
	// branch uuid
	TiXmlAttribute* pAttrib	=	pElement->FirstAttribute();
	if(pAttrib)
		gpApplication->Set_Branch_UUID( pAttrib->Value() );
	
	TiXmlNode* pChild;
	TiXmlText* pText;
	
	for ( pChild = pElement->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) {
		
		if(pChild->Type() == TiXmlNode::ELEMENT){
			
			if (stricmp("name", pChild->Value()) == 0) {
				
				TiXmlNode* pName = pChild->FirstChild();
				if(pName) {
					pText = pName->ToText();
					if(pText)
						gpApplication->Set_Branch_Name(pText->Value());
				}
			}
			
			else if (stricmp("description", pChild->Value()) == 0) {
				
				
				TiXmlNode* pSet_Branch_Description = pChild->FirstChild();
				if(pSet_Branch_Description) {
					pText = pSet_Branch_Description->ToText();
					if(pText)
						gpApplication->Set_Branch_Description(pText->Value());
				}
			}
			
			else if (stricmp("revision", pChild->Value()) == 0){
				
				TiXmlNode* pSet_Branch_Revision = pChild->FirstChild();
				if(pSet_Branch_Revision) {
					std::string sBranch_Revision = pSet_Branch_Revision->Value();
					gpApplication->Branch_Revision(atoi(sBranch_Revision.c_str()));
				}
			}
		}
	}
}
コード例 #9
0
void TiXmlElement::toStream( std::ostream& stream, int depth ) const
{
	int i;
	for ( i=0; i<depth; i++ )
		stream << "    ";

	stream << "<" << value;

	const TiXmlAttribute* attrib;
	for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() )
	{
		stream << " ";
		attrib->toStream( stream, depth );
	}

	// There are 3 different formatting approaches:
	// 1) An element without children is printed as a <foo /> node
	// 2) An element with only a text child is printed as <foo> text </foo>
	// 3) An element with children is printed on multiple lines.
	TiXmlNode* node;
	if ( !firstChild )
	{
		stream << " />";
	}
	else if ( firstChild == lastChild && firstChild->ToText() )
	{
		stream << ">";
		firstChild->toStream( stream, depth + 1 );
		stream << "</" << value << ">";
	}
	else
	{
		stream << ">";

		for ( node = firstChild; node; node=node->NextSibling() )
		{
			if ( !node->ToText() )
			{
				stream << "\n";
			}
			node->toStream( stream, depth+1 );
		}
		stream << "\n";
		for( i=0; i<depth; ++i )
			stream << "    ";
		stream << "</" << value << ">";
	}
}
コード例 #10
0
ファイル: xml_node.cpp プロジェクト: Snkrnryn/casadi
void XMLNode::addNode(TiXmlNode* n){
  if (!n) throw CasadiException("Error in XMLNode::addNode: Node is 0");

  // Save name
  setName(n->Value());
  
  // Save attributes
  int type = n->Type();  
  if(type == TiXmlNode::ELEMENT){
    if(n->ToElement()!=0){
      for(TiXmlAttribute* pAttrib=n->ToElement()->FirstAttribute(); pAttrib; pAttrib=pAttrib->Next()){
          setAttribute(pAttrib->Name(),pAttrib->Value());
      }
    }
  } else if(type == TiXmlNode::DOCUMENT) {
    // do nothing
  } else {
    throw CasadiException("XMLNode::addNode");
  }

  // Count the number of children
  int num_children = 0;
  for( TiXmlNode* child = n->FirstChild(); child != 0; child= child->NextSibling()){
    num_children++;
  }
  children_.reserve(num_children);
  
  // add children
  int ch = 0;
  for ( TiXmlNode* child = n->FirstChild(); child != 0; child= child->NextSibling(), ++ch){ 
      int childtype = child->Type();  

      if(childtype == TiXmlNode::ELEMENT){
        XMLNode newnode;
        newnode.addNode(child);
        children_.push_back(newnode);
        child_indices_[newnode.getName()] = ch;
      } else if(childtype == TiXmlNode::COMMENT){
        comment_ = child->Value();
      } else if(childtype == TiXmlNode::TEXT){
        text_ = child->ToText()->Value();
      } else if (childtype == TiXmlNode::DECLARATION){
        cout << "Warning: Skipped TiXmlNode::DECLARATION" << endl;
      } else {
        throw CasadiException("Error in XMLNode::addNode: Unknown node type");
      }
  }
}
コード例 #11
0
void TiXmlElement::Print( FILE* cfile, int depth ) const
{
    int i;
    assert( cfile );
    for ( i=0; i<depth; i++ ) {
        fprintf( cfile, "    " );
    }

    fprintf( cfile, "<%s", value.c_str() );

    const TiXmlAttribute* attrib;
    for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() )
    {
        fprintf( cfile, " " );
        attrib->Print( cfile, depth );
    }


    TiXmlNode* node;
    if ( !firstChild )
    {
        fprintf( cfile, " />" );
    }
    else if ( firstChild == lastChild && firstChild->ToText() )
    {
        fprintf( cfile, ">" );
        firstChild->Print( cfile, depth + 1 );
        fprintf( cfile, "</%s>", value.c_str() );
    }
    else
    {
        fprintf( cfile, ">" );

        for ( node = firstChild; node; node=node->NextSibling() )
        {
            if ( !node->ToText() )
            {
                fprintf( cfile, "\n" );
            }
            node->Print( cfile, depth+1 );
        }
        fprintf( cfile, "\n" );
        for( i=0; i<depth; ++i ) {
            fprintf( cfile, "    " );
        }
        fprintf( cfile, "</%s>", value.c_str() );
    }
}
コード例 #12
0
void AddTextElementRaw(TiXmlElement* node, const char* value)
{
	wxASSERT(node);
	wxASSERT(value && *value);

	for (TiXmlNode* pChild = node->FirstChild(); pChild; pChild = pChild->NextSibling())
	{
		if (!pChild->ToText())
			continue;

		node->RemoveChild(pChild);
		break;
	}

    node->LinkEndChild(new TiXmlText(value));
}
コード例 #13
0
ファイル: Options.cpp プロジェクト: Typz/FileZilla
void COptions::LoadOptionFromElement(TiXmlElement* pOption, std::map<std::string, unsigned int> const& nameOptionMap, bool allowDefault)
{
	const char* name = pOption->Attribute("name");
	if (!name)
		return;

	auto const iter = nameOptionMap.find(name);
	if (iter != nameOptionMap.end()) {
		if (!allowDefault && options[iter->second].flags == default_only)
			return;
		wxString value;

		TiXmlNode *text = pOption->FirstChild();
		if (text) {
			if (!text->ToText())
				return;

			value = ConvLocal(text->Value());
		}

		if (options[iter->second].flags == default_priority) {
			if (allowDefault) {
				scoped_lock l(m_sync_);
				m_optionsCache[iter->second].from_default = true;
			}
			else {
				scoped_lock l(m_sync_);
				if (m_optionsCache[iter->second].from_default)
					return;
			}
		}

		if (options[iter->second].type == number) {
			long numValue = 0;
			value.ToLong(&numValue);
			numValue = Validate(iter->second, numValue);
			scoped_lock l(m_sync_);
			m_optionsCache[iter->second] = numValue;
		}
		else {
			value = Validate(iter->second, value);
			scoped_lock l(m_sync_);
			m_optionsCache[iter->second] = value;
		}
	}
}
コード例 #14
0
ファイル: duXmlStatic.cpp プロジェクト: blueantst/dulib
dustring duXmlStatic::GetElementText(TiXmlElement *pElement)
{
	dustring strText = _T("");
	TiXmlNode *pChildNode = pElement->FirstChild();
	while (pChildNode)
	{
		if (pChildNode->Type() == TiXmlNode::TEXT)
		{
			TiXmlText *pXmlText = pChildNode->ToText();
			strText += pXmlText->Value();
		}
		
		pChildNode = pChildNode->NextSibling();
	}
	
	return strText;
}
コード例 #15
0
void BulletMLParserTinyXML::getTree(TiXmlNode* node) {
    if (node->ToComment() != 0) return;
    translateNode(node);

    TiXmlNode* child;
    for (child = node->FirstChild(); child; child = child->NextSibling()) {
        TiXmlText* text;
        if ((text = child->ToText()) != 0) {
            curNode_->setValue(text->Value());
            break;
        }

        getTree(child);
    }

    curNode_ = curNode_->getParent();
}
コード例 #16
0
ファイル: SE_ElementManager.cpp プロジェクト: 26597925/3DHome
void SE_UnitHeightHandler::handle(SE_Element* parent, TiXmlElement* xmlElement, unsigned int indent)
{
    SE_TextureCoordAnimation* anim = (SE_TextureCoordAnimation*)parent->getAnimation();
    if(anim == NULL)
        return;
    TiXmlNode* pChild;
    TiXmlNode* currNode = xmlElement;
    for(pChild = currNode->FirstChild() ; pChild != NULL ; pChild = pChild->NextSibling())
    {
        int t = pChild->Type();
        if(t != TiXmlNode::TINYXML_TEXT)
            return;
        TiXmlText* pText = pChild->ToText();
        const char* value = pText->Value();
        int h = atoi(value);
        anim->setUnitHeight(h);
    }
}
コード例 #17
0
void CKSXML_Read_Project::Read_Sample_Object(TiXmlElement* pElement)
{
	if ( !pElement ) return ;
	
	TiXmlAttribute* pAttrib	=	pElement->FirstAttribute();
	CSample_Data Sample_Data;
	
	// set sample uuid
	if(pAttrib)	{
		std::string sUUID = pAttrib->Value();
		Sample_Data.Set_UUID(sUUID);
	}
	
	TiXmlNode* pChild;
	TiXmlText* pText;
	
	for ( pChild = pElement->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) {
		
		if(pChild->Type() == TiXmlNode::ELEMENT){
			
			if (stricmp("name", pChild->Value()) == 0) {

				TiXmlNode* pName = pChild->FirstChild();
				if(pName) {
					pText = pName->ToText();
					if(pText)
						Sample_Data.Name(pText->Value());
				}
			}
			else if (stricmp("take", pChild->Value()) == 0) {
				
				CTake_Data* pTake_Data		=	Sample_Data.Get_Take_Data();
				// set take name
				pTake_Data->Screen_Name( Sample_Data.Name() );
				
				Read_Take_Object(pChild->ToElement(), pTake_Data);

			}
		}
	}
	
	// store sample data in list
	mSample_Data_List.push_back(Sample_Data);
}
コード例 #18
0
ファイル: TiXMLManager.cpp プロジェクト: LTears/rktotal
///////////////////////////////////////////////////////////////////////////////
// TiXMLManager::SetText
///////////////////////////////////////////////////////////////////////////////
// Description:
//		...
// Parameters:
//		const char* pcszText: 
//		const TiXmlNode* pNode /* = NULL */: 
// Return:
//		int: 
///////////////////////////////////////////////////////////////////////////////
int TiXMLManager::SetText(
	const char* pcszText, 
	TiXmlNode* pNode /* = NULL */)
{
    int nResult		= false;
    int nRetCode	= false;

	
	KAV_PROCESS_ERROR(pcszText);

	{
		TiXmlText	text(pcszText);
		TiXmlNode*	pChildNode = NULL;

		if (!pNode)
		{
			KAV_PROCESS_ERROR(m_pCurNode);
			pNode = m_pCurNode;
		}

		for (pChildNode = pNode->FirstChild(); pChildNode; pChildNode = pChildNode->NextSibling())
		{
			if (pChildNode->ToText())
				break;
		}
		
		if (pChildNode)
		{
			pNode->ReplaceChild(pChildNode, text);
		}
		else
			pNode->InsertEndChild(text);

	}


    nResult = true;

Exit0:	// fail exit

    return nResult;

}
コード例 #19
0
ファイル: JXml.cpp プロジェクト: luoxizhi/JLib
void JXmlNode::SetText(JString text, bool IsCData)
{
	string text_multi = ToUtf8String(text);
	if( m_pXmlElement ){
		if( !IsLeafNode ){
			m_pXmlElement->SetValue(text_multi);
		}else{
			TiXmlNode* child = NULL;
			while( child = m_pXmlElement->IterateChildren(child) ){
				if( IsTextNode(child) ){
					child->ToText()->SetValue(text_multi);
					return;
				}
			}
			TiXmlText txt(text_multi);
			txt.SetCDATA(IsCData);
			m_pXmlElement->InsertEndChild(txt);
		}
	}	
}
コード例 #20
0
ファイル: xmlfunctions.cpp プロジェクト: idgaf/FileZilla3
void AddTextElement(TiXmlElement* node, const wxString& value)
{
	wxASSERT(node);

	char* utf8 = ConvUTF8(value);
	if (!utf8)
		return;

	for (TiXmlNode* pChild = node->FirstChild(); pChild; pChild = pChild->NextSibling())
	{
		if (!pChild->ToText())
			continue;

		node->RemoveChild(pChild);
		break;
	}
	
    node->InsertEndChild(TiXmlText(utf8));
	delete [] utf8;
}
コード例 #21
0
ファイル: PluginXmlParser.cpp プロジェクト: LordGaav/sipxecs
TiXmlText*
PluginXmlParser::requireText (
    const TiXmlElement& elem,
	OsStatus* err)
{
	TiXmlNode* tn = (TiXmlNode*)elem.FirstChild();
	if (tn != NULL && tn->Type() == TiXmlNode::TEXT)
	{
		TiXmlText* t = tn->ToText();
		if (t->Value() != NULL)
		{
			return t;
		}
	}

	OsSysLog::add(FAC_SIP, PRI_ERR, "PluginXmlParser::requiredText "
		 "missing element text body %s ", elem.Value());
	*err = OS_FAILED;

	return NULL;
}
コード例 #22
0
const char* SimXMLDocument::getData()
{
   if(m_paNode.empty())
      return "";

   const int iFinalElement = m_paNode.size() - 1;
   TiXmlNode* pNode = m_paNode[iFinalElement];
   if(!pNode)
      return "";

   TiXmlNode * firstChild =  pNode->FirstChild();

   if(!firstChild)
	   return "";

   TiXmlText* text = firstChild->ToText();
   if( !text )
      return "";

   return text->Value();
}
コード例 #23
0
void TiXmlElement::Print( FILE* fp, int depth )
{
	int i;
	for ( i=0; i<depth; i++ )
		fprintf( fp, "    " );

	fprintf( fp, "<%s", value.c_str() );

	TiXmlAttribute* attrib;
	for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() )
	{	
		fprintf( fp, " " );
		attrib->Print( fp, 0 );
	}
	// If this node has children, give it a closing tag. Else
	// make it an empty tag.
	TiXmlNode* node;
	if ( firstChild )
	{ 		
		fprintf( fp, ">" );

		for ( node = firstChild; node; node=node->NextSibling() )
		{
	 		if ( !node->ToText() )
				fprintf( fp, "\n" );
			node->Print( fp, depth+1 );
		}
 		fprintf( fp, "\n" );
		for ( i=0; i<depth; i++ )
			fprintf( fp, "    " );
		fprintf( fp, "</%s>", value.c_str() );
	}
	else
	{
		fprintf( fp, " />" );
	}
}
コード例 #24
0
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
bool XmlElementImpl::setValueText(const String& text)
{
    TiXmlText* pText = NULL;
    TiXmlNode* pNode = NULL;
    for (pNode = FirstChild(); pNode; pNode = pNode->NextSibling())
    {
        pText = pNode->ToText();
        if (pText) break;
    }

    cvf::CharArray charArr = text.toUtf8();

    if (pText) 
    {
       pText->SetValue(charArr.ptr());
    }
    else
    {
        pText = new TiXmlText(charArr.ptr());
        LinkEndChild(pText);
    }

    return true;
}
コード例 #25
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( "data/utf8testout.xml", "r" );
			FILE* verify = fopen( "data/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鰊t鋘t咪鳇闹?"
                        "</?";

            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鰊t鋘t咪鳇闹?, 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;
}
コード例 #26
0
ファイル: proRataConfig.cpp プロジェクト: chongle/prorata
string ProRataConfig::getValue( TiXmlDocument &txdDoc, 
		const vector<string> &vsTagList )
{
	// Check to see if the provided XML node is valid.
	// If yes, extract the value from the node return it.
	// If no, return emply string.

	// creat a pointer to a node
	TiXmlNode * txnTemp = NULL;

	// check if the tree path is not empty
	if ( vsTagList.size() < 1 )
		return string("");
	
	// iterator for the input vsTagList
	vector<string>::const_iterator itrTagListItr;
	itrTagListItr = vsTagList.begin();

	// move the pointer to txddoc's first child with the specified tag name
	txnTemp = txdDoc.FirstChild( (*itrTagListItr ).c_str() );

	// check if this element exists
	if ( ! txnTemp )
	{
		cout << "ERROR: TAG\"" << (*itrTagListItr) << 
			"\" not found in the configuration file." << endl;
		return string("");
	}

	itrTagListItr++;

	// move the pointer down the hierarchial tree of elements
	for( ; itrTagListItr != vsTagList.end(); itrTagListItr++ )
	{

		txnTemp = txnTemp->FirstChild( (*itrTagListItr ).c_str() );

		if ( ! txnTemp )
		{
			cout << "ERROR: TAG\"" << (*itrTagListItr) << 
				"\" not found in the configuration file." << endl;
			return string("");
		}

	}

	// move the iterator back to point it to the last element name
	itrTagListItr--;

	/*
	 * inside the pointed element, there could be a mixture of
	 * text nodes, comment nodes and element nodes
	 * loop thru every nodes and for each text nodes, retrieve their text
	 * concatenate the text together and return them
	 */
	
	TiXmlText *txs;
	string sTemp = "";
	
	// point txnTemp to the child nodes and loop thru every child node
	for( txnTemp = txnTemp->FirstChild(); txnTemp; txnTemp = txnTemp->NextSibling() )
	{
		// if this node is pointing to a node of type TEXT, which equals 4 in enum NodeType
		if( txnTemp->Type() == 4 )
		{
			// cast txnTemp to a text node
			txs = txnTemp->ToText();
			// get txnTemp's value and then append it to sTemp
			if( txs )
				sTemp.append( txs->Value() );
		}
	}

	return sTemp;
}
コード例 #27
0
ファイル: xmlScript.cpp プロジェクト: ueverything/SyGame
/**
 * 构建这样的树结构
 *[A]------|
 * |	   |
 * |	  [A1]
 * |	   |
 * |	  [A2]----|
 * |	   |	[A21]----|
 * |       |      |      |
 * |	 NULL     NULL [A211]
 * |		         |
 * |		       [A212]
 * |			 |
 * |			NULL
 *[B]
 * */
tixmlCodeNode * tixmlCode::traceNode1(tixmlCodeNode *root,TiXmlNode *node)
{
    static std::string WHILE = "while";
    static std::string WHEN = "when";
    static std::string IF = "if";

    tixmlCodeNode * now = NULL;
    tixmlCodeNode * parent = root;
    tixmlCodeNode * pre = NULL;
    TiXmlNode *nowNode = node;
    while (!nowNode || nowNode->Type() != TiXmlNode::TINYXML_ELEMENT)
    {
        nowNode	= nowNode->NextSiblingElement();
    }
    if (!nowNode || nowNode->Type() != TiXmlNode::TINYXML_ELEMENT) return NULL;
    while (true)
    {
        if (!nowNode) // 当前节点为空
        {
            if (!parent) break;
            nowNode = parent->element->NextSiblingElement();
            parent = parent->parent;
            if (!parent) break;
            continue;
        }
        now = new tixmlCodeNode;
        if (!root)
        {
            root = now;
        }

        now->init(nowNode->ToElement());
//			printf("[script]处理节点 %s\n",now->nodeName.str());
        std::string& name = now->nodeName;
        if (name == WHILE || name == WHEN || name == IF)
        {
            void * code = getAction(now->getAttr("action"));
//				if (!code) printf("[script] 处理节点 %s 获取action 失败\n",now->getAttr("action"));
            now->setExtData(code);
        }
        else
        {
            void* code = getAction(now->nodeName.c_str());
//				if (!code) printf("[script] 处理节点 %s 获取action 失败\n",now->nodeName.str());
            now->setExtData(code);
        }
        if (pre && !pre->next)
        {
            pre->next = now;
//				printf("[script]---------------- 处理节点 %s 的下一个节点 %s-----------\n",pre->nodeName.str(),now->nodeName.str());
            pre = NULL;
        }
        now->parent = parent;
        if (now->parent)
        {
            if (parent->childs.size())
                pre = parent->childs.back();
            parent->childs.push_back(now);
        }
        TiXmlNode * child = nowNode->FirstChildElement();
        TiXmlNode *tchild = nowNode->FirstChild();
        if ((child == NULL || (tchild && tchild->Type() == TiXmlNode::TINYXML_TEXT)) && parent) // 如果当前无孩子 且有父亲节点
        {
            if (tchild)
            {
                // 获取节点的文档描述
                TiXmlText *pText = tchild->ToText();
                if (pText)
                {
                    //std::string str;
                    //str<<*nowNode;
                    //sys::sString value(str.c_str());
                    std::string value(pText->Value());
//						std::string vs = value.toXmlString();
                    now->setText(value);
                    //	printf("----获取文本内容 %s----\n",vs.str());
                }
            }
            if (pre && !pre->next)
            {
                pre->next = now;
                //	printf("[SCRIPT]--------------- 当前节点 %s 下一个节点%s -----------\n",pre->nodeName.str(),now->nodeName.str());
            }
            if (!now->element->NextSiblingElement())
            {
                pre = NULL;// TODO now;
                nowNode = parent->element->NextSiblingElement();
                parent = parent->parent;
                if (parent)
                {
                    //	printf("[script] 回溯到父节点:%s\n",parent->nodeName.str());
                }
                else break;
            }
            else
            {
                nowNode = now->element->NextSiblingElement();
            }
            if (parent)
            {
                // printf("[script] 当前节点%s无孩子节点 有父节点%s\n",now->nodeName.str(),parent->nodeName.str());
            }
            else
                break;

        }
        else if (child) // 当前有孩子
        {
            if (pre && !pre->next)
            {
                pre->next = now;
                //			printf("[SCRIPT]--------------- 当前节点 %s 下一个节点%s -----------\n",pre->nodeName.str(),now->nodeName.str());
            }
            nowNode = child; // 准备执行下一个节点
            //	printf("[script]当前节点有孩子节点 %s\n",now->nodeName.str());
            parent = now;
        }
        else // 当前无孩子 且 无 父亲节点 则退出
        {
            break;
        }
    }
    return root;
}
コード例 #28
0
TuringPtr generateTM(const std::string& fileName) {
    TiXmlDocument doc;
    std::string path = DATADIR + fileName;
    if(!doc.LoadFile(path.c_str()))
    {
        throw std::runtime_error("Error generating TM from XML: File not found!");
    }
    TiXmlElement* root = doc.FirstChildElement();
    std::string rootName;
    if(root == NULL)
    {
        throw std::runtime_error("Error generating TM from XML: Failed to load file: No root element.");
        doc.Clear();
    }
    rootName = root->Value();
    if (rootName != "TM") {
        throw std::runtime_error("Error generating TM from XML: Not a Turing Machine XML file!");
    }

    std::set<char> alphabet;
    std::set<char> tapeAlphabet;
    bool allFound = false;
    char blank = 0;
    for(TiXmlElement* elem = root->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement()) {  //find  alphabets and blank symbol
        std::string elemName = elem->Value();
        if (elemName == "InputAlphabet") {
            for(TiXmlElement* elemOfSigma = elem->FirstChildElement(); elemOfSigma != NULL; elemOfSigma = elemOfSigma->NextSiblingElement()) {
                std::string elemOfSigmaName = elemOfSigma->Value();
                if (elemOfSigmaName == "symbol") {
                    TiXmlNode* e = elemOfSigma->FirstChild();
                    TiXmlText* text = e->ToText();
                    if(text == NULL)
                        continue;
                    std::string t = text->Value();
                    if (t.size() != 1)
                        throw std::runtime_error("Error generating TM from XML: One input symbol per node please");
                    alphabet.insert(t.front());
                }
            }
        }
        if (elemName == "TapeAlphabet") {
            for(TiXmlElement* elemOfGamma = elem->FirstChildElement(); elemOfGamma != NULL; elemOfGamma = elemOfGamma->NextSiblingElement()) {
                std::string elemOfGammaName = elemOfGamma->Value();
                if (elemOfGammaName == "symbol") {
                    TiXmlNode* e = elemOfGamma->FirstChild();
                    TiXmlText* text = e->ToText();
                    if(text == NULL)
                        continue;
                    std::string t = text->Value();
                    if (t.size() != 1) {
                        throw std::runtime_error("Error generating TM from XML: One input symbol per node please");
                    }
                    tapeAlphabet.insert(t.front());
                }
            }
        }
        if (elemName == "Blank") {
            TiXmlNode* e = elem->FirstChild();
            TiXmlText* text = e->ToText();
            if(text == NULL)
                continue;
            std::string t = text->Value();
            if (t.size() != 1) {
                 throw std::runtime_error("Error generating TM from XML: One blank symbol please");
            }
            blank = t.front();
        }
        if (tapeAlphabet.size() && alphabet.size() && blank) { //All arguments necessary to construct TM found
            allFound = true;
            break;
        }
    }
    if (!allFound) {
         throw std::runtime_error("Error generating TM from XML: Alphabet, tape alphabet or blank symbol missing!");
        return nullptr;
    }
    TuringPtr TM(new TuringMachine(alphabet, tapeAlphabet, blank));

    for(TiXmlElement* elem = root->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement()) {  //find  alphabets and blank symbol
        std::string elemName = elem->Value();
        if (elemName == "States") {
            const char* attr = elem->Attribute("storage");
            bool hasStorage = false;
            std::vector<std::vector<char>> storages;
            if (attr) {
                std::string statesAttr(attr);
                if (statesAttr == "true")
                    hasStorage = true;
            }
            if (hasStorage) {
                for(TiXmlElement* elemOfQ = elem->FirstChildElement(); elemOfQ != NULL; elemOfQ = elemOfQ->NextSiblingElement()) {
                    std::string elemOfQName = elemOfQ->Value();
                    if (elemOfQName == "storage") {
                        if (elemOfQ->FirstChild() == NULL) {
                            storages.push_back(std::vector<char> ());
                            continue;
                        }
                        TiXmlNode* e = elemOfQ->FirstChild();
                        TiXmlText* text = e->ToText();
                        if(text == NULL)
                            continue;
                        std::string t = text->Value();
                        std::vector<char> thisStorage;
                        for (auto i : t)
                            thisStorage.push_back(i);
                        storages.push_back(thisStorage);
                    }
                }
            }
            for(TiXmlElement* elemOfQ = elem->FirstChildElement(); elemOfQ != NULL; elemOfQ = elemOfQ->NextSiblingElement()) {
                bool isStarting = false;
                bool isAccepting = false;
                std::string elemOfQName = elemOfQ->Value();
                if (elemOfQName == "state") {
                    const char* attr = elemOfQ->Attribute("start");
                    if (attr) {
                        std::string stateAttr(attr);
                        if (stateAttr == "true")
                            isStarting = true;
                    }
                    attr = elemOfQ->Attribute("accept");
                    if (attr) {
                        std::string stateAttr(attr);
                        if (stateAttr == "true")
                            isAccepting = true;
                    }
                    if (elemOfQ->FirstChild() == NULL) {
                         throw std::runtime_error("Error generating TM from XML: State without name");
                    }
                    TiXmlNode* e = elemOfQ->FirstChild();
                    TiXmlText* text = e->ToText();
                    if(text == NULL)
                        continue;
                    std::string t = text->Value();
                    if (!hasStorage)
                        TM->addState(t, isStarting, isAccepting);
                    else
                        for (auto i : storages)
                            TM->addState(t, isStarting, isAccepting, i);
                }
            }
        }
        if (elemName == "Transitions") {
            for(TiXmlElement* elemOfDelta = elem->FirstChildElement(); elemOfDelta != NULL; elemOfDelta = elemOfDelta->NextSiblingElement()) {
                std::string elemOfDeltaName = elemOfDelta->Value();
                if (elemOfDeltaName == "transition") {
                    std::string from = "";
                    std::string to = "";
                    std::vector<char> fromStorage;
                    std::vector<char> toStorage;
                    std::vector<char> read;
                    std::vector<char> write;
                    Direction dir = U;
                    for(TiXmlElement* elemOfTransition = elemOfDelta->FirstChildElement(); elemOfTransition != NULL; elemOfTransition = elemOfTransition->NextSiblingElement()) {
                        std::string elemOfTransitionName = elemOfTransition->Value();
                        if (elemOfTransitionName == "from") {
                            if (elemOfTransition->FirstChild() == NULL) {
                                continue;
                            }
                            TiXmlNode* e = elemOfTransition->FirstChild();
                            TiXmlText* text = e->ToText();
                            if(text == NULL)
                                continue;
                            std::string t = text->Value();
                            from = t;
                        }
                        if (elemOfTransitionName == "to") {
                            if (elemOfTransition->FirstChild() == NULL) {
                                continue;
                            }
                            TiXmlNode* e = elemOfTransition->FirstChild();
                            TiXmlText* text = e->ToText();
                            if(text == NULL)
                                continue;
                            std::string t = text->Value();
                            to = t;
                        }
                        if (elemOfTransitionName == "fromStorage") {
                            if (elemOfTransition->FirstChild() == NULL) {
                                continue;
                            }
                            TiXmlNode* e = elemOfTransition->FirstChild();
                            TiXmlText* text = e->ToText();
                            if(text == NULL)
                                continue;
                            std::string t = text->Value();
                            for (auto i : t)
                                fromStorage.push_back(i);
                        }
                        if (elemOfTransitionName == "toStorage") {
                            if (elemOfTransition->FirstChild() == NULL) {
                                continue;
                            }
                            TiXmlNode* e = elemOfTransition->FirstChild();
                            TiXmlText* text = e->ToText();
                            if(text == NULL)
                                continue;
                            std::string t = text->Value();
                            for (auto i : t)
                                toStorage.push_back(i);
                        }
                        if (elemOfTransitionName == "read") {
                            if (elemOfTransition->FirstChild() == NULL) {
                                continue;
                            }
                            TiXmlNode* e = elemOfTransition->FirstChild();
                            TiXmlText* text = e->ToText();
                            if(text == NULL)
                                continue;
                            std::string t = text->Value();
                            for (auto i : t)
                                read.push_back(i);
                        }
                        if (elemOfTransitionName == "write") {
                            if (elemOfTransition->FirstChild() == NULL) {
                                continue;
                            }
                            TiXmlNode* e = elemOfTransition->FirstChild();
                            TiXmlText* text = e->ToText();
                            if(text == NULL)
                                continue;
                            std::string t = text->Value();
                            for (auto i : t)
                                write.push_back(i);
                        }
                        if (elemOfTransitionName == "dir") {
                            if (elemOfTransition->FirstChild() == NULL) {
                                continue;
                            }
                            TiXmlNode* e = elemOfTransition->FirstChild();
                            TiXmlText* text = e->ToText();
                            if(text == NULL)
                                continue;
                            std::string t = text->Value();
                            if (t == "L")
                                dir = L;
                            else if (t == "R")
                                dir = R;
                            else
                                throw std::runtime_error("Error generating TM from XML: invalid direction" );
                        }
                    }
                    if (from.size() && to.size() && read.size() && write.size() && (dir == L || dir == R))
                        TM->addTransition(from, to, read, write, dir, fromStorage, toStorage);
                    else
                         throw std::runtime_error("Error generating TM from XML: Incomplete transition");
                }
            }

        }

    }
    for(TiXmlElement* elem = root->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement()) {  //find  alphabets and blank symbol
        std::string elemName = elem->Value();
        if (elemName == "StartState") {
            std::string stateName = "";
            std::vector<char> storage;
            for(TiXmlElement* elemOfSS = elem->FirstChildElement(); elemOfSS != NULL; elemOfSS = elemOfSS->NextSiblingElement()) {
                std::string elemOfSSName = elemOfSS->Value();
                if (elemOfSSName == "name") {
                    if (elemOfSS->FirstChild() == NULL) {
                        continue;
                    }
                    TiXmlNode* e = elemOfSS->FirstChild();
                    TiXmlText* text = e->ToText();
                    if(text == NULL)
                        continue;
                    stateName = text->Value();
                }
                if (elemOfSSName == "storage") {
                    if (elemOfSS->FirstChild() == NULL) {
                        continue;
                    }
                    TiXmlNode* e = elemOfSS->FirstChild();
                    TiXmlText* text = e->ToText();
                    if(text == NULL)
                        continue;
                    std::string t = text->Value();

                    for (auto i : t)
                        storage.push_back(i);
                }
            }
            if (stateName.size() != 0) {
                if (storage.size() == 0)
                    TM->indicateStartState(stateName);
                else
                    TM->indicateStartState(stateName, storage);
            }
            else
                throw std::runtime_error("Error generating TM from XML: No name for start state specified");
        }
        if (elemName == "AcceptingStates") {
            for(TiXmlElement* elemOfAccepting = elem->FirstChildElement(); elemOfAccepting != NULL; elemOfAccepting = elemOfAccepting->NextSiblingElement()) {
                std::string elemOfAcceptingName = elemOfAccepting->Value();
                if (elemOfAcceptingName == "state") {
                    std::string stateName = "";
                    std::vector<char> storage;
                    for(TiXmlElement* elemOfAccState = elemOfAccepting->FirstChildElement(); elemOfAccState != NULL; elemOfAccState = elemOfAccState->NextSiblingElement()) {
                        std::string elemOfAccStateName = elemOfAccState->Value();
                        if (elemOfAccStateName == "name") {
                            if (elemOfAccState->FirstChild() == NULL) {
                                continue;
                            }
                            TiXmlNode* e = elemOfAccState->FirstChild();
                            TiXmlText* text = e->ToText();
                            if(text == NULL)
                                continue;
                            stateName = text->Value();
                        }
                        if (elemOfAccStateName == "storage") {
                            if (elemOfAccState->FirstChild() == NULL) {
                                continue;
                            }
                            TiXmlNode* e = elemOfAccState->FirstChild();
                            TiXmlText* text = e->ToText();
                            if(text == NULL)
                                continue;
                            std::string t = text->Value();

                            for (auto i : t)
                                storage.push_back(i);
                        }
                    }
                    if (stateName.size() != 0) {
                        if (storage.size() == 0)
                            TM->indicateAcceptingState(stateName);
                        else
                            TM->indicateAcceptingState(stateName, storage);

                    }
                    else
                        throw std::runtime_error("Error generating TM from XML: No name for accepting state specified");
                }
            }
        }
    }
    return TM;
}
コード例 #29
0
ファイル: Options.cpp プロジェクト: alioxp/vc
void COptions::Init()
{
	if (m_bInitialized)
		return;
	simple_lock lock(m_mutex);
	m_bInitialized = TRUE;

	for (int i = 0; i < OPTIONS_NUM; ++i)
		m_sOptionsCache[i].bCached = FALSE;

	USES_CONVERSION;
	CStdString xmlFileName = GetExecutableDirectory() + _T("FileZilla Server.xml");
	char* bufferA = T2A(xmlFileName);
	if (!bufferA) {
		return;
	}

	TiXmlDocument document;

	WIN32_FILE_ATTRIBUTE_DATA status{};
	if (!GetStatus64(xmlFileName, status) ) {
		document.LinkEndChild(new TiXmlElement("FileZillaServer"));
		document.SaveFile(bufferA);
	}
	else if (status.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
		return;
	}

	if (!document.LoadFile(bufferA)) {
		return;
	}

	TiXmlElement* pRoot = document.FirstChildElement("FileZillaServer");
	if (!pRoot) {
		return;
	}

	TiXmlElement* pSettings = pRoot->FirstChildElement("Settings");
	if (!pSettings)
		pSettings = pRoot->LinkEndChild(new TiXmlElement("Settings"))->ToElement();

	TiXmlElement* pItem;
	for (pItem = pSettings->FirstChildElement("Item"); pItem; pItem = pItem->NextSiblingElement("Item")) {
		const char* pName = pItem->Attribute("name");
		if (!pName)
			continue;
		CStdString name(pName);

		const char* pType = pItem->Attribute("type");
		if (!pType)
			continue;
		CStdString type(pType);

		TiXmlNode* textNode = pItem->FirstChild();
		CStdString value;
		if (textNode && textNode->ToText())
			value = ConvFromNetwork(textNode->Value());
		else if (type == _T("numeric"))
			continue;

		for (int i = 0; i < OPTIONS_NUM; ++i) {
			if (!_tcscmp(name, m_Options[i].name)) {
				if (m_sOptionsCache[i].bCached)
					break;

				if (type == _T("numeric")) {
					if (m_Options[i].nType != 1)
						break;
					_int64 value64 = _ttoi64(value);
					if (IsNumeric(value))
						SetOption(i + 1, value64, false);
				}
				else {
					if (m_Options[i].nType != 0)
						break;
					SetOption(i + 1, value, false);
				}
				break;
			}
		}
	}
	ReadSpeedLimits(pSettings);

	UpdateInstances();
}
コード例 #30
0
void CKSXML_Read_Project::Read_Take_Object(TiXmlElement* pElement, CTake_Data* pTake_Data)
{

	if ( !pElement ) return ;
	
	// get take uuid
	TiXmlAttribute* pAttrib		=	pElement->FirstAttribute();
	if(pAttrib)		
		pTake_Data->Set_UUID(pAttrib->Value());   

	TiXmlNode* pChild;
	std::string s;
	
	
	for ( pChild = pElement->FirstChild(); pChild != 0; pChild = pChild->NextSibling()) {
		
		if(pChild->Type() == TiXmlNode::ELEMENT){
			s = "";
			if (stricmp("description", pChild->Value()) == 0) {
				
				TiXmlNode* pTake_Description = pChild->FirstChild();
				if(pTake_Description) {
					TiXmlText* pText = pTake_Description->ToText();
					if(pText){
						s = pText->Value();
						pTake_Data->Set_Description(s);
					}
				}
			}
			else if (stricmp("mode", pChild->Value()) == 0) {
				
				TiXmlNode* pTake_Mode = pChild->FirstChild();
				if(pTake_Mode) {
					TiXmlText* pText = pTake_Mode->ToText();
					if(pText){
						s = pText->Value();
						pTake_Data->Mode(s);
					}
				}
			}
			else if (stricmp("url", pChild->Value()) == 0) {
				
				TiXmlNode* pUrl = pChild->FirstChild();
				if(pUrl) {
					TiXmlText* pText = pUrl->ToText();
					if(pText){
						s = pText->Value();
						pTake_Data->URL(s);
					}
				}
			}
			
			else if (stricmp("mp3", pChild->Value()) == 0) {
				
				TiXmlNode* pMp3_Url = pChild->FirstChild();
				if(pMp3_Url) {
					TiXmlText* pText = pMp3_Url->ToText();
					if(pText){
						s = pText->Value();
						pTake_Data->MP3_URL(s);
					}
				}
			}
		}
	}
}