C++使用Boost库处理XML文件(2)

本文介绍了一种使用Boost库中的property_tree模块解析XML文件的方法。通过遍历XML节点及其属性,实现了对玩家信息数据的有效读取。代码示例展示了如何获取userInfo节点下的账户名、密码等属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<localinfo>
	<player_info>
		<userInfo account="1990wyb" isLastLogin="0" isSave="0" pass="">1</userInfo>
		<userInfo account="tt01234" isLastLogin="1" isSave="1" pass="272E7B">2</userInfo>
		<userInfo account="zhltang" isLastLogin="0" isSave="1" pass="2D1A3A">3</userInfo>
		<userInfo account="abest05" isLastLogin="0" isSave="1" pass="7BE688">4</userInfo>
	</player_info>
</localinfo>

#include <iostream>
using std::cout;
using std::endl;
using std::string;

#include <boost/property_tree/ptree.hpp>//ptree
using boost::property_tree::ptree;
#include <boost/property_tree/xml_parser.hpp>//read,write
#include <boost/foreach.hpp>//BOOST_FOREACH
ptree pt;
/*读取,去掉空格*/
read_xml("info.xml", pt, boost::property_tree::xml_parser::trim_whitespace, std::locale());
BOOST_FOREACH(ptree::value_type &child, pt.get_child("localinfo"))
{
	if ("<xmlattr>" == child.first)
	{
		cout << child.first << endl;
	}
	else if ("<xmlcomment>" == child.first)
	{
		cout << child.first << endl;
	}
	else if ("player_info" == child.first)
	{
		cout << child.first << endl;
		BOOST_FOREACH(ptree::value_type &node, child.second)
		{
			if ("<xmlattr>" == node.first)
			{
				cout << "\t" << node.first << endl;
			}
			else if ("<xmlcomment>" == node.first)
			{
				cout << "\t" << node.first << endl;
			}
			else if ("userInfo" == node.first)
			{
				cout << "\t" << node.first << endl;//节点名
				cout << "\t\t" << node.second.data() << endl;//节点值
				cout << "\t\t" << node.second.get<string>("<xmlattr>.account") << endl;//节点属性
				cout << "\t\t" << node.second.get<int>("<xmlattr>.isLastLogin") << endl;
				cout << "\t\t" << node.second.get<int>("<xmlattr>.isSave") << endl;
				cout << "\t\t" << node.second.get<string>("<xmlattr>.pass") << endl;
			}
		}
	}
}
运行结果:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值