---
title: "C++解析xml"
author: "HeLinHang"
date: "2013-10-09T20:11:35Z"
tags: []
categories: ["编程语言"]
slug: "c-xml"
draft: false
lastmod: "2013-10-09T20:11:35Z"
id: 1953951
url: "https://ibook.iteye.com/blog/1953951"
---

需要导入xml的文件，附件中有

 

需要解析的XML

 

 

```
<?xml version="1.0" encoding="UTF-8" ?>
<db>
	<db_ip>127.0.0.1</db_ip>	
	<db_port>3306</db_port>
	<dbname>test</dbname>
	<username>root</username>
	<password>root</password>
	
	<connection_num>20</connection_num>
</db>
```

 获得当前的exe路径

```
CString SessionFactory::getAppPath()
{
	TCHAR modulePath[MAX_PATH];
	GetModuleFileName(NULL, modulePath, MAX_PATH);
	CString strModulePath(modulePath);
	strModulePath = strModulePath.Left(strModulePath.ReverseFind(_T('\\')));
	return strModulePath;
}
```

 //解析xml

 

```
#include "../libs/tinyxml/tinystr.h"
#include "../libs/tinyxml/tinyxml.h"
```

 

 

```
void SessionFactory::loadDataBase(const char * fileName)
{
	CString tempPath=getAppPath();
    char * appPath=(LPSTR)(LPCTSTR)tempPath;
	string seperator = "\\";
	string fullPath = string(appPath)+seperator+fileName;

	TiXmlDocument doc(fullPath.c_str());
	doc.LoadFile();
	TiXmlElement * rootElement = doc.RootElement();
	OutMsg(rootElement->Value());
	TiXmlElement *dbIpElement = rootElement->FirstChildElement();
	dbIp = dbIpElement->FirstChild()->Value();
	
	TiXmlElement *dbPortElement = dbIpElement->NextSiblingElement();
	dbPort = dbPortElement->FirstChild()->Value();

	TiXmlElement *dbNameElement = dbPortElement->NextSiblingElement();
	dbName = dbNameElement->FirstChild()->Value();

	TiXmlElement *dbUsernameElement = dbNameElement->NextSiblingElement();
	username = dbUsernameElement->FirstChild()->Value();

	TiXmlElement *dbPasswordElement = dbUsernameElement->NextSiblingElement();
	password = dbPasswordElement->FirstChild()->Value();

	TiXmlElement *connectionNumElement = dbPasswordElement->NextSiblingElement();
	connectionNum = atoi(connectionNumElement->FirstChild()->Value());
	
}
```