看到boost里面有个property_ptree库不错,于是到网上下载了一个xml文件测试了一下,还真的比较好用,觉得比tinyXML库还好用,使用方法比较简单。
该库还可以解析ini, info, json文件,但我没试过。
xml文件大小为223kb,解析完如果不在命名窗口进行输出用了7s左右。
获得元素值使用ptree类的成员模板函数get,在模板参数中说明数据类型,在参数列表中填写路径,路径的表示也很简况,之间用点号分隔。
获得元素属性只需要在路径中的属性名称前面加上<xmlattr>标记就可以了,还有<xmlcomment>获得注释等。
对于有多个子元素的元素结点,我们可以使用getChild()来获得它的子结点,然后就可以像使用STL中的迭代器一样对子元素进行遍历操作。
注意get和getChild的路径参数,多调试一下也是极好的。
具体用法可以参照下面的代码:
注意在使用get方法时最好给出第二个参数用作默认值,这样如果没有找到该属性,函数会返回该默认值,否则,程序会崩溃,最好对getChild
方法进行异常的捕获,以提高程序的鲁棒性。
文件结构复杂度适中:
解析代码如下:
<span style="font-family:Courier New;font-size:14px;"><span style="font-family:Courier New;font-size:12px;">#include <vector>
#include <iterator>
#include <string>
#include <algorithm>
#include <tchar.h>
#include <basetsd.h>
#include <iostream>
#include "boost/timer.hpp"
#include "boost/property_tree/ptree.hpp"
#include "boost/property_tree/xml_parser.hpp"
#include "boost/property_tree/exceptions.hpp"
using namespace std;
struct _head
{
wstring revMajor;
wstring revMinor;
wstring name;
wstring version;
wstring date;
wstring north;
wstring south;
wstring east;
wstring west;
wstring maxR