您的位置:首页 > 其它

使用tinyxml进行XML文件解析

2013-08-30 09:40 295 查看
最近在做关于XML文件解析,在网上查找了资料,自己在这里总结一下。

我是在vs2008环境上做的项目,从网上可以直接下载tinyxml库,将tinystr.h,tinyxml.h,tinystr.cpp,tinyxml.cpp,tinyxmlerror.cpp,tinyxmlparser.cpp

这六个文件放到工程目录里。

这是我的需要解析的config.xml文件(在这里我需要解析出ip):

<?xml version="1.0" encoding="utf-8"?>

<configuration>

<MainDll></MainDll>

<ChannelDlls>

<ChannelDll>TestClient.dll</ChannelDll>

</ChannelDlls>

<ManagerIPAddress>192.168.4.17</ManagerIPAddress>

</configuration>

好了,来看解析的代码吧



XMLParse.h

#ifndef XMLPARSE_H
#define XMLPARSE_H
#include <windows.h>
#include <string>
#include <atlstr.h>

using namespace std;
CString GetAppPath();
bool ReadXmlFile(string& szFileName,char* ManagerIPAddress);

#endif

XMLParse.cpp

#include "XMLParse.h"
#include "tinyxml.h"
#include "tinystr.h"
//#include <string>
//
//using namespace std;

CString GetAppPath()
{//获取应用程序根目录
TCHAR modulePath[MAX_PATH];
GetModuleFileName(NULL, modulePath, MAX_PATH);
CString strModulePath(modulePath);
strModulePath = strModulePath.Left(strModulePath.ReverseFind(_T('\\')));
return strModulePath;
}

bool ReadXmlFile(string& szFileName,char* ManagerIPAddress)
{//读取Xml文件,并遍历
try
{
CString appPath = GetAppPath();//当工程的属性中的字符集设置为unicode时,CString表现为wchar_t
string seperator = "\\";
string fullPath = appPath.GetBuffer(0) +seperator+szFileName;
//创建一个XML的文档对象。

TiXmlDocument *myDocument = new TiXmlDocument(fullPath.c_str());
myDocument->LoadFile();
//获得根元素,即Persons。
TiXmlElement *RootElement = myDocument->RootElement();
//输出根元素名称,即输出Persons。
printf("%s\n", RootElement->Value());

TiXmlElement *CurrentPerson = RootElement->FirstChildElement();
while(CurrentPerson)
{
printf("%s\n",CurrentPerson->Value());
if(0==strcmp(CurrentPerson->Value(),"ManagerIPAddress"))//这里获得当前节点的值进行比较
{
printf("%s\n",CurrentPerson->FirstChild()->Value());//获得ip值
memcpy(ManagerIPAddress,CurrentPerson->FirstChild()->Value(),strlen(CurrentPerson->FirstChild()->Value()));
return true;
}

CurrentPerson = CurrentPerson->NextSiblingElement();
}
}
catch (string& e)
{
return false;
}
return true;
}


main.cpp

#include "XMLParse.h"
int main()
{
char ManagerIPAddress[64]="127.0.0.1";
string XMLFileName = "config.xml";
memset(ManagerIPAddress,0,sizeof(ManagerIPAddress));
ReadXmlFile(XMLFileName,ManagerIPAddress);
if(strlen(ManagerIPAddress)<=0)//此处可以修改一个更好的值,yangyijing 20130829
{
return -1;
}
printf("ManagerIPAddress=%s\n",ManagerIPAddress);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: