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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值