#include "stdafx.h"
#include <iostream>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>
void printTree(ptree root, int curLayer)
{
BOOST_FOREACH(ptree::value_type &v1, root){
if(v1.first == "<xmlattr>"){
BOOST_FOREACH(ptree::value_type &vAttr, v1.second){
int layer = curLayer;
while (layer--)
{
cout<<'\t';
}
cout<<vAttr.first<<"="<<vAttr.second.data()<<endl;
}
}
else
{
int layer = curLayer;
while (layer--)
{
cout<<'\t';
}
cout<<v1.first;
if (v1.second.empty() == true)
{
cout<<"="<<v1.second.data();
}
cout<<endl;
if (v1.second.empty() == false)
{
printTree(v1.second, curLayer+1);
}
}
}
}
int main(void)
{
ptree pt;
read_xml("miniWidget.xml", pt);
printTree(pt, 0);
return 0;
}
<?xml version="1.0" encoding="utf-8"?>
<minigui>
<layout>
<widget widgetType="PAGE" manType="stack" name="desktop">
<property>
<x1>0</x1>
<y1>0</y1>
<x2>480</x2>
<y2>272</y2>
</property>
<skin>page-common</skin>
<child>
<widget widgetType="PAGE" manType="list" name="PAGE0">
<property>
<x1>0</x1>
<y1>0</y1>
<x2>480</x2>
<y2>272</y2>
</property>
<skin>page-common</skin>
<child>
<widget widgetType="MENU" manType="none" name="PAGE0-MENU0">
<property>
<x1>122</x1>
<y1>38</y1>
<x2>442</x2>
<y2>272</y2>
<itemNum>5</itemNum>
<itemGap>2</itemGap>
<itemFace>item0Face</itemFace>
</property>
<skin>menu0Face</skin>
</widget>
</child>
</widget>
<widget widgetType="PAGE" manType="list" name="PAGE1">
<property>
<x1>0</x1>
<y1>0</y1>
<x2>480</x2>
<y2>272</y2>
</property>
<skin>page-common</skin>
<child>
<widget widgetType="VSLIDE" manType="none" name="PAGE1-LIST0">
<property>
<x1>442</x1>
<y1>38</y1>
<x2>380</x2>
<y2>272</y2>
<blockFace>blockFace</blockFace>
<blockHeight>25</blockHeight>
</property>
<skin>slide-common</skin>
</widget>
<widget widgetType="BTN" manType="none" name="PAGE1-BTN0">
<property>
<x1>0</x1>
<y1>0</y1>
<x2>92</x2>
<y2>38</y2>
</property>
<skin>btn-common</skin>
</widget>
<widget widgetType="BTN" manType="none" name="PAGE1-BTN1">
<property>
<x1>400</x1>
<y1>0</y1>
<x2>480</x2>
<y2>38</y2>
</property>
<skin>btn-common</skin>
</widget>
</child>
</widget>
</child>
</widget>
</layout>
<uiStyle>
<btn-common>
<group name="common" default="true">
<face faceType="image">
<src>Destinator.png</src>
<bndInsrc>
<x1>59</x1>
<y1>1482</y1>
<x2>119</x2>
<y2>1517</y2>
</bndInsrc>
<wrap>9zone</wrap>
</face>
</group>
<group name="push">
<face faceType="image">
<src>Destinator.png</src>
<bndInsrc>
<x1>0</x1>
<y1>1482</y1>
<x2>58</x2>
<y2>1517</y2>
</bndInsrc>
<wrap>9zone</wrap>
</face>
</group>
</btn-common>
<page-common>
<group name="common" default="true">
<face faceType="image">
<src>About.png</src>
<bndInsrc>
<x1>0</x1>
<y1>0</y1>
<x2>480</x2>
<y2>272</y2>
</bndInsrc>
<wrap>comm</wrap>
</face>
</group>
</page-common>
</uiStyle>
</minigui>
最关键的地方在于理解v1.second, ptree::value_type 是一个pair。first是一个字符串。其值是xml节点名,如果那个节点是个属性,则其值为,也可以看出ptree把属性当作一个子节点。second是ptree类型。对于ptree的查找我一直没找到合适的方法。如果各位兄弟有示例代码,请告知。谢谢。