使用boost读取XML文件详细介绍
2019/7/10 22:53:46
本文主要是介绍使用boost读取XML文件详细介绍,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
boost读取XML文件
boost中提供了对配置文件读取的支持,它就是:property_tree。
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表示支持宽字符。
例如:
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>
我要读取它的数据:
#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 getchar(); return 0; }
运行的显示为: ID is 1 Try Default100 name is :fansy http://blog.csdn.net//fansongy http://weibo.com//fansongy
config.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>
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
这篇关于使用boost读取XML文件详细介绍的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-28pyqt 怎么打包整个项目-icode9专业技术文章分享
- 2024-09-28laravel Commands 创建带有参数的 Artisan 命令的步骤和示例-icode9专业技术文章分享
- 2024-09-28antd怎么实现渲染tiff图片-icode9专业技术文章分享
- 2024-09-28英文半角中划线和中文全角的中划线有什么区别-icode9专业技术文章分享
- 2024-09-28nvm npm 和node 他们之间有什么关系-icode9专业技术文章分享
- 2024-09-28Node Version Manager (nvm)使用教程-icode9专业技术文章分享
- 2024-09-28nvm命令太慢,是什么原因-icode9专业技术文章分享
- 2024-09-28Kotlin 如何增加、删除和修改 MutableStateFlow 中的值。-icode9专业技术文章分享
- 2024-09-28Kotlin的stateFlow.update 写法介绍-icode9专业技术文章分享
- 2024-09-28kotlin 怎么获取当前时间格式-icode9专业技术文章分享