<?xml version="1.0" encoding="utf-8"?>
<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>
</player_info>
<setting soundVol="3" lagFrame="0" videoEnhance="1"/>
<MessageBoxTitle extraCmd="" ecWparam="" ecLparam="">可更新</MessageBoxTitle>
</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_FOREACHptree pt;
/*读取,去掉空格*/
read_xml("info.xml", pt, boost::property_tree::xml_parser::trim_whitespace, std::locale());
//增加节点(位置,节点名、值、属性和值)
pt.add("localinfo.user","temp");
pt.put("localinfo.user.<xmlattr>.account","0610");
//删除节点(位置)
auto nodes = pt.get_child("localinfo");
ptree::iterator it = pt.get_child("localinfo").begin();
it++;
nodes.erase(it);
//修改节点值
pt.put("localinfo.MessageBoxTitle","不可更新");
//修改节点属性值
pt.put("localinfo.MessageBoxTitle.<xmlattr>.extraCmd","file");
/*写入,缩进,编码*/
boost::property_tree::xml_writer_settings<string> settings =
boost::property_tree::xml_writer_make_settings<string>('\t', 1, "utf-8");
write_xml("A.xml",pt, std::locale(), settings);运行结果:

//复杂一点的例子
//增加一个userInfo节点,account->testabc, isLastLogin->0, isSave->0, pass->"abcdef", 值为4
auto pos = pt.get_child("localinfo.player_info");
ptree tempnode;
tempnode.add("<xmlattr>.account","testabc");
tempnode.add("<xmlattr>.isLastLogin", "0");
tempnode.add("<xmlattr>.isSave", "0");
tempnode.add("<xmlattr>.pass", "abcdef");
tempnode.put("",4);
pt.add_child("localinfo.player_info.userInfo",tempnode);
//删除account为"1990wyb"的userInfo节点
for (auto node = pt.get_child("localinfo.player_info").begin(); node != pt.get_child("localinfo.player_info").end(); ++node)
{
if (node->first == "userInfo")
{
if (node->second.get<string>("<xmlattr>.account") == "1990wyb")
{
pt.get_child("localinfo.player_info").erase(node);
break;
}
}
}
//修改account为"tt01234"的userInfo节点,isSave->0
for (auto node = pt.get_child("localinfo.player_info").begin(); node != pt.get_child("localinfo.player_info").end(); ++node)
{
if (node->first == "userInfo")
{
if (node->second.get<string>("<xmlattr>.account") == "tt01234")
{
node->second.put("<xmlattr>.isSave","0");
break;
}
}
}
/*写入,缩进,编码*/
boost::property_tree::xml_writer_settings<string> settings =
boost::property_tree::xml_writer_make_settings<string>('\t', 1, "utf-8");
write_xml("A.xml",pt, std::locale(), settings);运行结果:

本文介绍了一种使用Boost.PropertyTree库操作XML文件的方法,包括读取、增加、删除及修改节点等内容。通过实例展示了如何对XML文件进行复杂的操作。
2556

被折叠的 条评论
为什么被折叠?



