简单的cmakelist运用以及c++中tinyXml的使用
大致学习了一下CMakeLists,刚好想用一下c++中的tinyXml,就写了一个简单的工程
上面这个是工程目录的目录结构: cmakeTest文件夹 相当于workSpace,也就是主目录 build文件夹 是cmake生成的中间文件的存放地 tinyXml文件夹 是tinyXml源码的地方,这个文件夹内有一个子目录的CMakeLists文件 CmakeLists 就是主目录的cmake文件 main.cpp 就是主文件 menu.xml 是测试解析xml的测试xml文件
先看menu.xml文件内容
<?xml version="1.0"?>
<breakfast_menu>
<foods>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>light Belgian waffles covered with strawberries and whipped cream</description>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
<calories>900</calories>
</food>
<food>
<name>French Toast</name>
<name>Test</name>
<price>$4.50</price>
<description>thick slices made from our homemade sourdough bread</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
<calories>950</calories>
</food>
</foods>
</breakfast_menu>
主要有breakfast_menu、foods、food三个node
然后看一下main.cpp文件如何使用tinyXml库来解析xml
#include <iostream>
#include "tinyXml/tinyxml.h"
using namespace std;
void readXml()
{
TiXmlDocument doc("C:\\workSpace\\xmlHander\\cmakeTest\\menu.xml");
if (!doc.LoadFile())
{
std::cout << "failed to load xml file!" << std::endl;
const char * error = doc.ErrorDesc();
cout << error << endl;
}
TiXmlHandle handler(&doc);
TiXmlElement* desc = handler.FirstChild("breakfast_menu").FirstChild("foods").Child("food",3).Child("name",1).ToElement();
if (desc)
{
cout << "success" << endl;
}
else
{
cout << "error" << endl;
}
cout << desc->GetText() << endl;
}
int main()
{
readXml();
}
最后看一下两个目录下的CMakeLists文件
aux_source_directory(. DIR_LIB_SRCS)
add_library (tinyXml ${DIR_LIB_SRCS})
cmake_minimum_required(VERSION 3.0)
project(XmlParser)
set(CMAKE_C_COMPILER "C:\\mingw64\\bin\\gcc")
set(CMAKE_CXX_COMPILER "C:\\mingw64\\bin\\g++")
add_definitions("-Wall -g")
aux_source_directory(. DIR_SRCS)
add_subdirectory(tinyXml)
add_executable(xmlParser ${DIR_SRCS})
target_link_libraries(xmlParser tinyXml)
以上代码均运行正常,注释中的描述可能有不对的地方,发现的话烦请各位指出,感激!
|