Boost.xml_parser读写内容简单的Xml

//范例如下,注释随代码

#include   
#include   
#include   
using namespace std;  

#include   
#include   
#include   
#include   
using namespace boost::property_tree;  

typedef map ssMap;

class CBoostXmlUtil{
public:
	static ssMap* ReadXml(string& xml){
		ptree oTree, oRoot;
		xml_parser::read_xml(xml, oTree);
		oRoot = oTree.get_child("Root");

		ssMap* pConfigMap = new ssMap;
		for(ptree::iterator it = oRoot.begin(); it != oRoot.end(); it++){
			string strKey = it->first; boost::algorithm::trim(strKey);
			ptree oNode = it->second; string strValue = oNode.data(); boost::algorithm::trim(strValue);
			pConfigMap->insert(pair(strKey, strValue));
		}
		return pConfigMap;
	}
	static bool WriteXml(ssMap& mpXml, string& xml){
		ptree oNode;
		for(ssMap::iterator it = mpXml.begin(); it != mpXml.end(); it++){
			oNode.put("Root." + it->first, it->second);//"Root"后的"."不可省略
		}
		write_xml(xml.c_str(), oNode);
		return true;
	}
};

/*
  
	scott
	tigger
	127.0.0.1
	1521
  
*/
void Tst01()
{
	string sSrcXml("D:\\Projects\\BoostPro\\Debug\\Src.xml");
	ssMap* pMap = CBoostXmlUtil::ReadXml(sSrcXml);
	if(pMap == NULL){
		cout << "Xml Node Not Found !" << endl;
		return;
	}
	for(ssMap::iterator it = pMap->begin(); it != pMap->end(); it++){
		cout << it->first << " : " << it->second << endl;
	}
	cout << endl;

	string sDstXml("D:\\Projects\\BoostPro\\Debug\\Dst.xml");
	CBoostXmlUtil::WriteXml((*pMap), sDstXml);

	delete pMap;
}

/*
  
      
        张三  
        30  
      
 
*/
//读取固定路径下单一值
void Tst02()
{
	ptree oTree;//open xml and read information to oTree;
	read_xml("D:\\Projects\\BoostPro\\Debug\\Stu1.xml", oTree);
	//read value to var by a path  
	string sName = oTree.get("root.students.name");
	int iAge = oTree.get("root.students.age");
	cout << "Name : " << sName << ", Age : " << iAge << endl << endl;
}

/*
  
      
        张三  
        李四  
		王五  
      

*/
//遍历单层孩子
void Tst03()
{
	ptree oTree;//open xml and read information to oTree
	read_xml("D:\\Projects\\BoostPro\\Debug\\Stu3.xml", oTree);
	ptree oStudents = oTree.get_child("root.students");
	for(ptree::iterator it = oStudents.begin(); it != oStudents.end(); it++){
		//此时it->first的值为路径名:name 
		string sName = it->second.get_value();
		cout << sName << endl;
	}
}

/*
 
  first student  
  second student  
  third student 

*/
//遍历包含属性的孩子
void Tst04()
{
	ptree oTree;//open xml and read information to oTree
	read_xml("D:\\Projects\\BoostPro\\Debug\\Stu3WithAttr.xml", oTree);
	ptree oRoot = oTree.get_child("root");
	for(ptree::iterator it = oRoot.begin(); it != oRoot.end(); it++){
		ptree oStudent = it->second; //获取列表中的一个学生的节点
		cout << oStudent.get("") << endl;//获取值
		cout << "Name : " << oStudent.get(".name");//获取属性
		cout << ", Age : " << oStudent.get(".age") << endl << endl;//获取属性
	}
}

你可能感兴趣的:(Boost(开放的源码,强大的工具))