boost::ptree;boost::xml_parser

 

<?xml version="1.0" encoding="utf-8"?>
<localinfo>
    <player_info>
        <userInfo account="1990wyb" isLastLogin="0" isSave="0"/>
    </player_info>
    <PopupMessages>
        <MSGID_NOUPDATE>无可用更新</MSGID_NOUPDATE>
    </PopupMessages>
</localinfo>

 

 

#include <cstdio>
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <set>
#include <exception>
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
#include <boost/typeof/typeof.hpp>
using namespace std;
using namespace boost;
namespace pt = boost::property_tree;

int main()
{
    pt::ptree tree;

    string m_file = "./ss.xml";

    try
    {
        //pt::read_xml(m_file, tree);
        //读取,去掉空格
        pt::read_xml(m_file, tree, boost::property_tree::xml_parser::trim_whitespace, std::locale());

        //1
        std::string strName = tree.get<std::string>("localinfo.PopupMessages.MSGID_NOUPDATE");
        cout << strName << endl;

        //2
        //自动推导类型
        BOOST_AUTO(child, tree.get_child("localinfo2"));//获取根节点的子节点
        BOOST_AUTO(pos, child.begin());
        for (; pos != child.end(); ++pos)//循环遍历
        {
            if ("player_info" == pos->first)//player_info
            {
                cout << pos->first << endl;
                BOOST_AUTO(nodes, pos->second.get_child(""));
                BOOST_AUTO(node, nodes.begin());
                for (; node != nodes.end(); ++node)
                {
                    if ("<xmlattr>" == node->first) {}
                    else if ("<xmlcomment>" == node->first) {}
                    else
                    {
                        //3 节点属性的值,不存在, 返回默认值
                        cout << "\t\t" << node->second.get<string>("<xmlattr>.account", "null") << endl;
                        cout << "\t\t" << node->second.get<string>("<xmlattr>.isLastLogin", "0") << endl;
                        cout << "\t\t" << node->second.get<string>("<xmlattr>.xxxx", "not exit") << endl;
                    }
                }
            }
        }
    }
    catch (std::exception &e)
    {
        cout << "Error: " << e.what() << endl;
    }
}

 

posted @ 2021-03-07 20:11  osbreak  阅读(152)  评论(0编辑  收藏  举报