boost库——XML解析

浅尝boost库的xml解析代码——XML是树形结构的数据交换语言,boost库中用的数据结构也是树

记录以下boost库的xml解析代码

 

 

//-----------------------xml文件:debug.log.xml----------------------//


debug.log

    Finance
    Admin
    HR

2


//-----------------------xml文件:create.log.xml--------------------//


debug.log
2

Admin
Finance
HR






#include 
#include 
#include 

#include 
#include 
#include 

using namespace std;
using namespace boost;

struct xml_parser
{
	std::string m_file;
	int m_level;
	std::set m_modules;
	void load(const std::string& filename);
	void save(const std::string& filename);
};

//
//debug.log< / filename>
//
//Finance< / module>
//Admin< / module>
//HR< / module>
//< / modules>
//< level>2 < / level >
//< / debug>

void xml_parser::load(const std::string& filename)
{
	//创建一个空的ptree对象
	using boost::property_tree::ptree;
	ptree pt;

	//加载xml文件到ptree对象
	read_xml(filename, pt);

	m_file = pt.get("debug.filename");

	m_level = pt.get("debug.level", 0);

	BOOST_FOREACH(ptree::value_type & v, pt.get_child("debug.modules"))  //get_child获取的是平级child的集合,每一个元素是一个平级child
		m_modules.insert(v.second.data());
}

void xml_parser::save(const std::string& filename)
{
	using boost::property_tree::ptree;
	ptree pt;
	ptree pchild;
	
	//放 log filename到property tree中
	pt.put("debug.filename", m_file);  //设置节点的值
	
	pchild.put("author", "zhangsan");
	//pt.put_child("debug.filename", pchild);
	

	//放 debug level到property tree中
	pt.put("debug.level", m_level);  //设置节点的值
	pt.add("debug.level..price", "100");

	//循环设置module的值
	BOOST_FOREACH(const std::string & name, m_modules)
		pt.add("debug.modules.module", name);

	

	write_xml(filename, pt);

}

void save(const std::string& filename)
{
	using boost::property_tree::ptree;
	ptree pt;
	ptree pchild;

	std::string attr = "..";
	std::string root = "root";
	pt.add(root, "");
	std::string attrname = "school";
	pt.add(root + attr + attrname, "WuHan University");

	std::string child = ".student";
	ptree &pc = pt.add(root + child, "");
	pc.put(".name", "zhangsan");
	pc.put_value("shabi");


	auto setting = boost::property_tree::xml_writer_make_settings('\t', 1);

	write_xml(filename, pt, std::locale(), setting);
}


int main()
{
	xml_parser objxml;
	objxml.load("debug.log.xml");
	cout << objxml.m_file << endl;
	cout << objxml.m_level << endl;
	BOOST_FOREACH(std::string str, objxml.m_modules)
	{
		cout << "module" << str << endl;
	}

	objxml.save("create.log.xml");

	save("abstractoperator.xml");

	return 0;
}

 

 

你可能感兴趣的:(#,xml)