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原文链接:https://www.f2er.com/xml/299022.html