BOOST之property_tree 及解析XML详解

摘要:

property_tree是一个保存了多个属性值的属性数据结构,可以用类似路径的简单方式访问任意节点的属性,而且每个节点都可以用类似STL的风格遍历子节点。property_tree特别适合于应用程序的配置数据处理,可以解析xml、ini、json和info四个格式的文本数据。

在处理四种格式的文件时,除包含头文件、读文件、写文件时有部分区别外,其他对文件内部数据操作时基本一致(因为文件格式都基本一直)。实际上,property_tree内部使用的就是一个小巧快速的开源XML解析器——rapidxml。


使用方法:

1)不同:(XXX分别代码xml、json、ini、info)

#include 
#include 
using namespace boost::property_tree;
void main(void)
{
	ptree pt;
	read_XXX("./test.XXX", pt);	// 读文件
	// ....其他操作
	write_XXX(cout, pt);		// 写文件,有两种格式:
					// void write_XXX(const string &, Ptree &pt);
					// void write_XXX(basic_ostream &, Ptree &pt);
}


2)相同:(下面以xml为基础详细介绍,其他三种类型没测试过,囧~)

测试的XML文件:test.xml


	
	
	
		
		
			abc
			efg
			hij
		
		
			klm
			nop
			qrs
		
	


测试代码:

#include 
#include 
#include 
#include 
#include 

using namespace std;
using namespace boost::property_tree;

int main(void)
{
	char szXmlFile[] = "E:/test.xml";

	string strTmp;

	ptree pt;
	xml_parser::read_xml(szXmlFile, pt);

	BOOST_AUTO(child, pt.get_child("config.file"));
	for (BOOST_AUTO(pos, child.begin()); pos != child.end(); ++pos)
	{
		strTmp.clear();
		if ("" == pos->first)
		{
			strTmp = pos->second.get("title");		// 输出:windows
			cout<second.get("size");		// 输出:10Mb
			cout<second.get("noexits", "This is default");	
			cout<" == pos->first)
		{
			strTmp = pos->second.data();		// 第一次输出:File First Comment
			cout<second.get_child(""));
			for (BOOST_AUTO(nextpos, nextchild.begin()); nextpos != nextchild.end(); ++nextpos)
			{
				strTmp.clear();
				if ("" == nextpos->first)
				{
					strTmp = nextpos->second.get("attr");	// 输出:directory
					cout<" == nextpos->first)
				{
					strTmp = nextpos->second.data();		// 输出:Paths Comment
					cout<second.get(".title");
					cout<second.data();
					cout<

测试结果:

BOOST之property_tree 及解析XML详解_第1张图片

分析:从上述测试中可以看出,BOOST封装的RapidXml开源库,是将XML文件内容解析为一个树状结构。比如说本例中使用的节点“config.file”,具有五个子节点:一个属性子节点、两个注释子节点、两个数据子节点,且顺序为属性→注释→数据
①属性子节点:
每个节点只有一个属性子节点,是一对多关系,即一个属性子节点对应多个属性!
"if ("" == pos->first)",然后获取属性的值则为“pos->second.get("title")”和“pos->second.get("size")”。注意这里获取属性,不再是".title",因为此时pos已经指向本节点,不再需要用""递推到属性子节点!
②注释子节点:节点可以有多个属性子节点,是一对一关系!!!
if ("" == pos->first)“,获取属性则“pos->second.data()”;
③数据子节点:这种节点又可以重新看做是一个节点,下面会对应属性子节点、注释子节点、数据子节点。但注意“pos->second.get_child("")”是返回当前节点的所有子节点(包含属性、注释、数据),而“pt.get_child("config.file")“是返回file节点下所有节点(包含属性、注释、数据)。


参考资料:
1、boost::property_tree


你可能感兴趣的:(BOOST)