加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

tinyxml的安装和使用

发布时间:2020-12-15 22:59:39 所属栏目:百科 来源:网络整理
导读:tinyxml(官网:http://www.grinninglizard.com/tinyxml/)是一个解析xml的c++库,短小惊悍型的,开源软件各个版本差异比较大,我这次下载的版本为tinyxml-2版本,同学们阅读文章时,记得核对版本,下面讲述下其安装和使用。 1 下载tinyxml,下载地址为:http:

tinyxml(官网:http://www.grinninglizard.com/tinyxml/)是一个解析xml的c++库,短小惊悍型的,开源软件各个版本差异比较大,我这次下载的版本为tinyxml-2版本,同学们阅读文章时,记得核对版本,下面讲述下其安装和使用。

1 下载tinyxml,下载地址为:http://sourceforge.net/projects/tinyxml/,下载之后unzip解压,我的解压路径为:/home/lclin/tinyxml

2 默认的Makefile是生成其测试程序的,为了使用,我们需要生成静态库,此时需要修改Makefile,按下面方式修改即可。

${OUTPUT}: ${OBJS}
	${AR} $@ ${LDFLAGS} ${OBJS} ${LIBS} ${EXTRA_LIBS}

修改之后,执行make,可生成相关的lib文件,生成的lib文件为 libtinyxml.a

下面完成我们的测试程序:

<Config>
<Item Key="Host"  Value="127.0.0.1"/>
<Item Key="Port"  Value="10001"/>
<Item Key="LogPath"  Value="/tmp/calog/"/>
<Item Key="LogLevel"  Value="0"/>
</Config>
C++实现代码
#ifndef _TINY_XML_TEST_H_
#define _TINY_XML_TEST_H_

#include <string>
#include <fstream> 
#include <iostream>
#include "tinyxml.h"

class CTinyXmlTest
{
public:
	CTinyXmlTest()
	{
	}
	~CTinyXmlTest()
	{
	}

	int loadConf(const char*cXmlFilePath)
	{
		assert(cXmlFilePath);

		std::ifstream ifile;
		ifile.open(cXmlFilePath);
		if (!ifile.is_open())
		{
			std::cerr << "Config File Not Exist!!" << std::endl;
			return -1;
		}
		TiXmlDocument* configDocument = new TiXmlDocument();
		configDocument->LoadFile(cXmlFilePath);
		TiXmlElement* rootElement = configDocument->RootElement(); //ConfigCenter
		TiXmlElement* itemElement = rootElement->FirstChildElement(); //Item
		std::cout << "Config Content:" << std::endl;
		int i = 0;
		std::string strKey,strValue;

		while (itemElement)
		{
			TiXmlAttribute* attributeOfItem = itemElement->FirstAttribute();

			while (attributeOfItem)
			{
				if (0 == i)
				{
					strKey = std::string(attributeOfItem->Value());
				}
				else if (1 == i)
				{
					strValue = std::string(attributeOfItem->Value());
					std::cout << strKey << ":" << strValue;
					i = 0;
				}
				attributeOfItem = attributeOfItem->Next();
				i++;
			}
			i = 0;
			itemElement = itemElement->NextSiblingElement();
			std::cout<<std::endl;
		}

		delete configDocument;
		configDocument = NULL;

		std::cout << "Config Dump Finished!!" << std::endl;

		return 0;
	}
};

int main(int argc,char**argv)
{
	CTinyXmlTest oTest;
	oTest.loadConf(argv[1]);

	return 0;
}
#endif//_TINY_XML_TEST_H_

按如下方式编译代码:

g++ -I /home/lclin/tinyxml tinyxmltest.cpp -L /home/lclin/tinyxml -ltinyxml

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读