<boost> xml文件解析 例2

参考:https://blog.csdn.net/fansongy/article/details/9026407

config.xml

<?xml version="1.0" encoding="utf-8"?>
<con>
  <id>1</id>
  <name>fansy</name>
  <urls>
    <url>http://blog.csdn.net//fansongy</url>
    <url>http://weibo.com//fansongy</url>
  </urls>
</con>

cpp文件

#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/typeof/typeof.hpp>  
using namespace std;
using namespace boost::property_tree;
int  main()
{
    ptree pt;
    read_xml("conf.xml",pt);     //读入一个xml文件
    cout<<"ID is "<<pt.get<int>("con.id")<<endl;  //读取节点中的信息
    cout<<"Try Default"<<pt.get<int>("con.no_prop",100)<<endl;  //如果取不到,则使用默认值
    ptree child = pt.get_child("con");    //取一个子节点
    cout<<"name is :"<<child.get<string>("name")<<endl;    //对子节点操作,其实跟上面的操作一样
    
    child = pt.get_child("con.urls");
    for(BOOST_AUTO(pos,child.begin());pos != child.end();++pos)  //boost中的auto
     {
         cout<<"\t"+pos->second.data()<<endl;
     }
    pt.put("con.name","Sword");    //更改某个键值
    pt.add("con.urls.url",http://www.baidu.com); //增加某个键值
    write_xml("conf.xml",pt);    //写入XML
    return 0;
}

编译

g++ config.cpp -I/root/boost_1_75_0_build/include

执行结果

ID is 1
Try Default100
name is :fansy
	http://blog.csdn.net//fansongy
	http://weibo.com//fansongy
cat conf.xml 
<?xml version="1.0" encoding="utf-8"?>
<con>
	<id>1</id>
	<name>Sword</name>
	<urls>
		<url>http://blog.csdn.net//fansongy</url>
		<url>http://weibo.com//fansongy</url>
		<url>http://www.baidu.com</url>
	</urls>
</con>
posted @ 2021-03-22 15:47  kouei_kou  阅读(106)  评论(0)    收藏  举报