近期项目需要用到xml文件和属性树,使用boost库中的read_xml()函数,发现一些问题,现总结如下:
1. read_xml()函数在文件boost/property_tree/xml_parser.hpp中,使用了开源的软件rapid_xm库;
2. 使用该函数,需要编译boost库,我的boost环境配置:
1) windows:include:D:\Program Files\boost\boost_1_55_0
libs: D:\Program Files\boost\boost_1_55_0\stage\lib
2) Linux:include:/home/chenchen/boost_1_55_0
libs: /home/chenchen/boost_1_55_0/stage/lib
3. 源文件test.cpp包含头文件:
1) #include <boost/property_tree/ptree.hpp>
2) #include<boost/property_tree/xml_parser.hpp>
声明:using namespace boost::property_ptree;
4. 源程序 test.cpp vs2012下编译运行通过
#include <string>
#include <iostream>
using namespace boost::property_tree;
using namespace boost::system;
int main( int argc, char* argv[] )
{
ptree pt;
try
{
boost::property_tree::xml_parser::read_xml("D:\\工作文档\\UmpEvent\\Debug\\conf.xml", pt);
}
catch(xml_parser::xml_parser_error sysError)
{
std::cout << "Error: " <<sysError.what() << std::endl;
}
std::cout << pt.get<std::string>("conf.theme") <<std::endl;
}
5. 需要注意的问题:
1) windows下read_xml()函数中xml文件的位置描述字符串中,分隔文件夹位置需要用\\,读取绝对路径xml文件是,需要在路径前加反义字符\或者/,如可执行文件相同路径下的xml文件路径为
\.\\conf.xml
否则会报cannot open file错误
2) Linux下可以使用绝对位置,也可以使用相对位置,且不用加转义符号,即“conf.xml”或者“/root/conf.xml”均可
3) 编译时需要包含头文件和静态库文件,Linux下使用-I$(INLCUDES_PATH)和-L$(LIBS_PATH)
以上,如有疑问可以给我留言。2015-01-21