C++ 加载.xml文件

来源:互联网 发布:php redis 阻塞队列 编辑:程序博客网 时间:2024/05/22 02:01

首先写一个ProductNameConfig.xml


<?xml version="1.0" encoding="GB2312" ?>
<Root>
    <Product>
<Parameter ProductID="CY" ProductName="棉纱" />
    </Product>
</Root>


首先需要在头文件包含以下两个头文件:

#include "tinyxml.h"

#include "tinystr.h"


#define RETURN_OK 0
#define  RETURN_ERROR -1


class TiXmlElement;

class TiXmlNode;

class TiXmlDocument;


创建一个DataSet类,下面直接写实现部分。

类头文件中定义TiXmlDocument* pDoc;

加载.xml文件

int CDataSet::LoadProductInfo()
{
char chMainPath[MAX_PATH + 1] = {0};
GetModuleFileName(NULL, chMainPath, MAX_PATH);
char *pos = strrchr(chMainPath, '\\');
*(pos + 1) = '\0';
std::string strTmpPath=chMainPath;
// GetCurrentDirectory(MAX_PATH,path);
strTmpPath+="ini\\ProductNameConfig.xml";


FILE* fp = fopen(strTmpPath.c_str(),"r");
if(fp ==NULL)
{
//LOG_TRACE(LOG_ERROR_LEVEL,"INIT","Please Check %s is Existing!",strTmpPath.c_str());
return RETURN_ERROR;
}
else
{
fclose(fp);
fp=NULL;
}


if(ParseConfigFile(strTmpPath.c_str()) == RETURN_ERROR)
{
//LOG_TRACE(LOG_ERROR_LEVEL,"INIT","ParseConfigFile Failed",strTmpPath.c_str());
return RETURN_ERROR;
}
return ROHONDB_OK;
}


int CDataSet::ParseConfigFile(const char* szFileName)
{
pDoc = new TiXmlDocument(szFileName);
bool bSuccess = pDoc->LoadFile();
if (!bSuccess)
{
//LOG_TRACE(LOG_ERROR_LEVEL,"PARSEFILE","Load File Failed");
delete pDoc;
pDoc = NULL;
return RETURN_ERROR;
}


//读取Root节点
TiXmlNode* RootNode = pDoc->FirstChild("Root");
TiXmlElement* pPluginElement = NULL;


if ((pPluginElement = RootNode->FirstChildElement("Product"))!= NULL)
{
if (ReadProductElement(pPluginElement) == RETURN_ERROR)
{
return RETURN_ERROR;
}
}
else
{
//LOG_TRACE(LOG_ERROR_LEVEL,"PARSEFILE","Product Element is not finded");
return RETURN_ERROR;
}


return RETURN_OK;
}


int CDataSet::ReadProductElement(TiXmlElement* pPLuginElement)
{
ASSERT(pPLuginElement);
TiXmlElement* pParameter=NULL;
for (pParameter=pPLuginElement->FirstChildElement("Parameter");pParameter!=NULL;pParameter=pParameter->NextSiblingElement())
{
m_mapProductNameField.insert(std::pair<std::string,std::string>(pParameter->Attribute("ProductID"),pParameter->Attribute("ProductName")));
}


if (m_mapProductNameField.size() ==0)
{
///LOG_TRACE(LOG_ERROR_LEVEL,"REDPRODUCT","Product Element size is zero");
return RETURN_ERROR;
}


return RETURN_OK;
}