使用tinyxml进行XML文件解析

最近在做关于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;
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值