使用boost的property_tree解析XML

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

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

basic_ptree 是property_tree的核心基础。其接口像std::list。可以执行很多基本的元素操作,比如使用begin()、end()等。

此外还加入了操作属性树的get()、get_child()、get_value()、data()等额外的操作。

basic_ptree有两个重要的内部定义self_type和value_type。self_type是basic_ptree模板实例化后自身的类型,它也是子节点的类型。value_type是节点的数据结构,它是一个std::pair,它含有属性名(first)和节点自身(second)。

通常不使用basic_ptree,而是使用预定义的typedef。ptree、wptree、iptree、wiptree。前缀i表示忽略大小写,前缀w表示支持宽字符。

例如要解析如下XML文件config.xml

<config>
	<!-- File Fisrt Comment -->
	<serverName>www.zoudaokou.com</serverName>
	<http name="a" url="http://www.zoudaokou.com/a.rar"/>
	<http name="b" url="http://www.zoudaokou.com/b.rar"/>
</config>

解析代码如下

#include <iostream>
#include <string>

#include "boost/property_tree/xml_parser.hpp"
#include "boost/typeof/typeof.hpp"

using namespace std;

int main()
{
	boost::property_tree::ptree pt; //定义一个存放xml的容器指针
	boost::property_tree::read_xml("config.xml", pt); //读入目录下config.xml文件 入口在pt这个指针
	boost::property_tree::ptree child = pt.get_child("config.serverName"); //这里定义个一个节点child指针,并将指针指向config下一层的serverName
	string serverName = pt.get<string>("config.serverName"); //获取config下一层serverName的值
	cout << "serverName:" << serverName << endl;

	BOOST_AUTO(config, pt.get_child("config"));
	for (BOOST_AUTO(config_ele, config.begin()); config_ele != config.end(); ++config_ele)  
	{
		if ("<xmlcomment>" == config_ele->first) //遍历config节点,找到注释节点
		{
			cout << "comment:" << config_ele->second.data() << endl;
		}
		else if ("serverName" == config_ele->first) //遍历config节点,找到名为serverName的节点
		{
			cout << "serverName:" << config_ele->second.data() << endl;
		}
		else if ("http" == config_ele->first) //遍历config节点,找到名为http的节点
		{
			BOOST_AUTO(http, config_ele->second.get_child("")); //此处不需要填结点名,但引号不能省.这里是获取该节点下所有子节点的意思
			for (BOOST_AUTO(http_ele, http.begin()); http_ele != http.end(); ++http_ele)
			{
				if ("<xmlattr>" == http_ele->first) //遍历config下层的http节点,找到属性节点
				{
					cout << "name:" << http_ele->second.get<string>("name") << 
						", url:" << http_ele->second.get<string>("url") << endl;
				}
			}
		}
	}
	return 0;
}

运行结果:

serverName:www.zoudaokou.com
comment: File Fisrt Comment
serverName:www.zoudaokou.com
name:a, url:http://www.zoudaokou.com/a.rar
name:b, url:http://www.zoudaokou.com/b.rar

2 Comments

  1. test说道:

    【原创】【独发ename】国际域名落米采集分析工具 http://www.dnbbs.com/thread-145429-1-1.html (出处: 域名论坛)
    软件已经找不到了,还有没有?跪求~