现在的位置: 首页 > 综合 > 正文

write to TinyXML

2013年04月18日 ⁄ 综合 ⁄ 共 1534字 ⁄ 字号 评论关闭
#include "tinyxml.h"
#include "tinystr.h"
#include <string>
int main()
{
	TiXmlDocument *pDoc;
	TiXmlElement *pRootElem;
	int num = 0;
	std::string m_FileName = "123.xml";
	pDoc = new TiXmlDocument(m_FileName.c_str());
	if (NULL == pDoc)
	{
		throw std::runtime_error("TiXmlDocument can't be opened!");
	}
	TiXmlDeclaration decl(("1.0"), ("gb2312"), ("yes"));  
	pDoc->LinkEndChild(&decl);
	pRootElem = new TiXmlElement(("Messages"));
	if (NULL == pRootElem)
	{
		throw std::runtime_error("pRootElem can't be opened!");
	}
	pDoc->LinkEndChild(pRootElem);
	for (;num < 10;)
	{
		TiXmlElement *pMessageElement = new TiXmlElement("Message");
		if (NULL == pMessageElement)
		{
			throw std::runtime_error("pMessageElement can't be opened!");
		}
		TiXmlElement *pMessageLenElement = new TiXmlElement("MessageLen");
		if (NULL == pMessageLenElement)
		{
			throw std::runtime_error("pMessageLenElement can't be opened!");
		}
		TiXmlElement *pMessageContentElement = new TiXmlElement("MessageContent");
		if (NULL == pMessageContentElement)
		{
			throw std::runtime_error("pMessageContentElement can't be opened!");
		}
		pMessageElement->SetAttribute("ID",++num); 
		pRootElem->LinkEndChild(pMessageElement);
		pMessageElement->LinkEndChild(pMessageLenElement);
		pMessageElement->LinkEndChild(pMessageContentElement);
		TiXmlText *MessageLength = new TiXmlText("11");
		if (NULL == MessageLength)
		{
			throw std::runtime_error("MessageLength can't be opened!");
		}
		//std::string lStr(str,len);
		TiXmlText *MessageContent = new TiXmlText("22");
		if (NULL == MessageContent)
		{
			throw std::runtime_error("MessageContent can't be opened!");
		}
		pMessageLenElement->LinkEndChild(MessageLength);
		pMessageContentElement->LinkEndChild(MessageContent);
	}
	pDoc->SaveFile();
}

抱歉!评论已关闭.