使用boost的property_tree解析内存缓冲区中的XML

上一篇文章中是使用boost的property_tree来读取本地XML文件的方式来解析的,见http://www.zoudaokou.com/index.php/archives/628,但在某些情况下,我是从网络上接收到XML数据的,如果再将XML数据存在文件中,再用read_xml读取文件,就显示多余了,本文介绍直接使用property_tree将内存中保存的XML数据解析出来。

在property_tree中读取XML内容的函数是read_xml,它的参数有两种形式:

//第一种形式
template<class Ptree> void read_xml(std::basic_istream<typename Ptree::key_type::value_type> &stream,
                  Ptree &pt,
                  int flags = 0)
//第二种形式
template<class Ptree> void read_xml(const std::string &filename,
                  Ptree &pt,
                  int flags = 0,
                  const std::locale &loc = std::locale())

第二种形式中第一个参数是文件名,在第一种形式中,可以看到第一个参数为std::basic_istream &stream,那么我们可以使用字符串流istrstream,它是间接继承于basic_istream的,字符串流可以将内存中的数据保存起来,然后在调用read_xml的时候传入istrstream进行解析。

例如在内存中的XML文件内容如下:

<config>
    <serverName>www.zoudaokou.com</serverName>
</config>

解析内存中的XML文件代码如下:

#include <iostream>
#include <string>
#include <strstream>

#include "boost/property_tree/xml_parser.hpp"

using namespace std;

int main()
{
	//下面这段是将文件读取内存中,模拟从网络上接收到XML数据存入内存
	int buffLen = 10240;
	char buffer[10240];
	FILE* pFile = fopen("config.xml", "rb");
	if (pFile)
	{
		buffLen = fread(buffer, sizeof(char), 10240, pFile);
		fclose(pFile);
	}

	boost::property_tree::ptree pt; //定义一个存放xml的容器指针
	istrstream iss(buffer, buffLen);
	boost::property_tree::read_xml(iss, pt); //读取内存中的数据 入口在pt这个指针
	string serverName = pt.get<string>("config.serverName"); //获取config下一层serverName的值
	cout << "serverName:" << serverName << endl;

	return 0;
}

Comments are closed.