#include "StdAfx.h"
#include "MyXmlMgr.h"
#include "GlobalDefine.h"
#include "LogMgr.h"
#include "FileMgr.h"
#include "GlobalFunction.h"
CMyXmlMgr::CMyXmlMgr(void)
{
}
CMyXmlMgr::~CMyXmlMgr(void)
{
}
/*生成格式例子
Double
1000
Double
0
Double
0
Double
0
*/
//递归函数
void CMyXmlMgr::SaveXmlItem(TiXmlElement *RootElement,CMyXmlItem &XmlItem)
{
int size = XmlItem.m_XmlItemVec.size();
if(size==0)//子节点,递归的终点
{
TiXmlText *XmlValContent = new TiXmlText(XmlItem.m_XmlItemName);
RootElement->LinkEndChild(XmlValContent);
}
else
{
TiXmlElement *ItemElement = new TiXmlElement(XmlItem.m_XmlItemName);
if(XmlItem.m_XmlItemAttributeName!="")//设置属性值
{
ItemElement->SetAttribute(XmlItem.m_XmlItemAttributeName, XmlItem.m_XmlItemAttributeVal);
}
RootElement->LinkEndChild(ItemElement);
for(int k=0;kLinkEndChild(pDeclaration);
//创建根元素并连接。
TiXmlElement *RootElement = new TiXmlElement(XmlItem.m_XmlItemName);
myDocument->LinkEndChild(RootElement);
//递归
int size = XmlItem.m_XmlItemVec.size();
for(int k=0;kSaveFile(CStringToLPCSTR(FilePath));
delete myDocument;
}
catch (string& e)
{
CString log =e.c_str();
log = "ReadXmlErr-->" + log;
gLogMgr->WriteDebugLog(log);
return;
}
}
//递归函数
void CMyXmlMgr::ReadXmlItem(TiXmlElement *RootElement,CMyXmlItem &XmlItem)
{
XmlItem.m_XmlItemName = RootElement->Value();
TiXmlAttribute* XmlItemAttribute = RootElement->FirstAttribute();//只取一个属性值
if(XmlItemAttribute!=NULL)
{
XmlItem.m_XmlItemAttributeName = XmlItemAttribute->Name();
XmlItem.m_XmlItemAttributeVal = XmlItemAttribute->Value();
}
//第一个子节点
TiXmlElement *XmlElement = RootElement->FirstChildElement();
if(XmlElement==NULL)//最后一层
{
CMyXmlItem XmlChildItem;
XmlChildItem.m_XmlItemName = RootElement->GetText();
XmlItem.AddXmlItem(XmlChildItem);
}
else
{
//遍历当前层
for(;XmlElement != NULL;XmlElement = XmlElement->NextSiblingElement())
{
CMyXmlItem XmlChildItem;
XmlItem.AddXmlItem(XmlChildItem);
vector&XmlItemVec = XmlItem.m_XmlItemVec;
int size = XmlItemVec.size();
//递归
ReadXmlItem(XmlElement,XmlItemVec[size-1]);
}
}
}
//从xml 文件中恢复XmlItem
bool CMyXmlMgr::ReadXmlItemFromFile(CString FilePath,CMyXmlItem &XmlItem)
{
try
{
XmlItem.m_XmlItemVec.clear();
//文件不存在直接退出,避免报错
CFileMgr FileMgr;
if(!FileMgr.IsFileExist(FilePath))
{
return false;
}
//创建一个XML的文档对象。
TiXmlDocument *myDocument = new TiXmlDocument(CStringToLPCSTR(FilePath));
myDocument->LoadFile();
//获得根元素
TiXmlElement *RootElement = myDocument->RootElement();
//递归
ReadXmlItem(RootElement,XmlItem);
delete myDocument;
}
catch (string& e)
{
CString log =e.c_str();
log = "ReadXmlErr-->" + log;
gLogMgr->WriteDebugLog(log);
return false;
}
return true;
}