所用函数等理论知识见博客:http://t.csdnimg.cn/p9OS2
实战目标:
读取内容如下的.xml文件
实战代码:
首先需要搞定配置文件路径,这个功能不难,利用GetModuleFileNameA()、find_last_of()与substr()配合就可以得到,这里不赘述。至于这几个函数作用,见置顶博客。
得到配置文件路径后就可以读取啦。其中用到TinyXML库,如何使用参见博客:http://t.csdnimg.cn/9ts6C
函数实现如下:
void CParameter::GetParam(string strConfPath)
{
TiXmlDocument myXML(strConfPath.c_str());
if (!myXML.LoadFile())
{
LOG(INFO) << "请检查配置文件名与程序名称是否一致!" << endl;
system("pause");
return;
}
TiXmlElement* RootElement = myXML.RootElement();
for (TiXmlElement* StuElement = RootElement->FirstChildElement(); StuElement != NULL; StuElement = StuElement->NextSiblingElement())
{
if (strcmp(StuElement->Value(), "PlatInfo") == 0)
{
for (TiXmlElement* ComElement = StuElement->FirstChildElement(); ComElement != NULL; ComElement = ComElement->NextSiblingElement())
{
PlatInfo stPlatInfo;
memset(&stPlatInfo, 0x00, sizeof(stPlatInfo));
stPlatInfo.nComNum = Helper::HConvert::ToNumber<int>(ComElement->Attribute("Number"));
for (TiXmlElement* ItemElement = ComElement->FirstChildElement(); ItemElement != NULL; ItemElement = ItemElement->NextSiblingElement())
{
if (strcmp(ItemElement->Attribute("priority"), "ComProtocol") == 0)
{
stPlatInfo.nComProtocal = Helper::HConvert::ToNumber<int>(ItemElement->Attribute("value"));
continue;
}
if (strcmp(ItemElement->Attribute("priority"), "IpAddress") == 0)
{
stPlatInfo.strIpAddress = Helper::HConvert::ToString(ItemElement->Attribute("value"));
continue;
}
if (strcmp(ItemElement->Attribute("priority"), "Port") == 0)
{
stPlatInfo.nPort = Helper::HConvert::ToNumber<int>(ItemElement->Attribute("value"));
continue;
}
if (strcmp(ItemElement->Attribute("priority"), "CalPort") == 0)
{
stPlatInfo.nCalPort = Helper::HConvert::ToNumber<int>(ItemElement->Attribute("value"));
continue;
}
if (strcmp(ItemElement->Attribute("priority"), "StartAddress") == 0)
{
stPlatInfo.nStartAddress = Helper::HConvert::ToNumber<int>(ItemElement->Attribute("value"));
continue;
}
if (strcmp(ItemElement->Attribute("priority"), "platDirInvl") == 0)
{
stPlatInfo.nPlatDirInvl = Helper::HConvert::ToNumber<int>(ItemElement->Attribute("value"));
continue;
}
if (strcmp(ItemElement->Attribute("priority"), "PlatAngleStart") == 0)
{
stPlatInfo.strPlatAngleStart = Helper::HConvert::ToString(ItemElement->Attribute("value"));
continue;
}
if (strcmp(ItemElement->Attribute("priority"), "PlatAngleEnd") == 0)
{
stPlatInfo.strPlatAngleEnd = Helper::HConvert::ToString(ItemElement->Attribute("value"));
continue;
}
if (strcmp(ItemElement->Attribute("priority"), "PlatInitialAngle") == 0)
{
stPlatInfo.strPlatInitialAngle = Helper::HConvert::ToString(ItemElement->Attribute("value"));
continue;
}
}
listPlat.push_back(stPlatInfo);
}
continue;
}
}
}