首页 > 代码库 > boost.property_tree

boost.property_tree

//made by davidsu33
//boost.property_tree是一个保存了多个属性值的树形数据结构
//boost.property_tree可以解析xml ini json和info四种格式的文本

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>

#include <boost/typeof/typeof.hpp>

#include <iostream>
#include <string>
#include <cassert>
using namespace std;

void putline(const char * str)
{
	cout<<str<<endl;
}

void putline(const std::string& str)
{
	cout<<str<<endl;
}

void parse_xml()
{
	std::string filename = "./conf.xml";

	typedef boost::property_tree::ptree PTree;
	PTree pt;
	boost::property_tree::read_xml(filename, pt);

	string theme = pt.get<string>("conf.theme");
	int guiID = pt.get<int>("conf.gui");

	//int id = pt.get_value<int>();
	assert(guiID == 1);
	
	//不存在属性返回默认值
	int def = pt.get<int>("conf.no", 100000);
	assert(def = 100000);

	BOOST_AUTO(childs2, pt.get_child("conf.urls"));
	PTree childs = pt.get_child("conf.urls");

	//???
	//int count = pt.count("urls");
	//assert(count == 3);

	//读取多子节点的数据
	BOOST_AUTO(it, childs.begin());
	BOOST_AUTO(iend, childs.end());
	for (;
		it != iend; ++it)
	{
		//迭代器指向ptree的value_type,
		//它的second成员是子节点自身
		//cout<<it->second.get_value<string>()<<endl;

		//等价于
		cout<<it->second.data()<<endl;
	}

	//读取XML的属性,不支持声明的读取
	//string decl = pt.get<string>(""); //读取XML声明
	
	BOOST_ASSERT(pt.get<string>("conf.gui.<xmlattr>.lib") == "QT");
	BOOST_ASSERT(pt.get<int>("conf.theme.<xmlattr>.id") == 1002);
	BOOST_ASSERT(pt.get<string>("conf.<xmlcomment>") == "this is conf comment");

	//貌似不支持CDATA,测试未通过
	//std::string xmltext = pt.get<string>("conf.<xmltext>");
	//BOOST_ASSERT(pt.get<string>("conf.<xmltext>") == "字符数据-character data");
}

int _tmain(int argc, _TCHAR* argv[])
{
	parse_xml();
	getchar();
	return 0;
}

boost.property_tree