Boost: xml_parser process xml
--------- Debug_settings.xml --------
[Html]
<Root>
<Strage name = "asd" alias = "13" classId = "13.22"> r
<Id> 12 </id>
<Name> "jack" </name>
<Accout> 0001 "</accout>
</Strage>
<Strage name = "abbasd" alias = "14" classId = "14.22"> abb
<Id> 13 </id>
<Name> "toni" </name>
<Accout> 0002 "</accout>
</Strage>
<Strage name = "assasd" alias = "15" classId = "15.44"> ass
<Id> 14 </id>
<Name> "hate" </name>
<Accout> 0003 "</accout>
</Strage>
</Root>
-------- Main. cpp --------
[Html]
# Include <boost/property_tree/ptree. hpp>
# Include <boost/property_tree/xml_parser.hpp>
# Include <boost/algorithm/string. hpp>
# Include <boost/foreach. hpp>
# Include <string>
# Include <set>
# Include <vector>
# Include <exception>
# Include <iostream>
Using namespace std;
Static const string str_node_name [] = {"id", "name", "accout "};
Struct xmlStageDetail
{
String id;
String name;
String accout;
};
Int load (const char * filename, vector <xmlStageDetail> * m_xml_detail)
{
XmlStageDetail xml_stage_detail;
Using boost: property_tree: ptree;
Ptree pt;
Ptree root;
Try
{
Read_xml (filename, pt );
Cout <"Get data" <pt. data () <endl;
Root = pt. get_child ("root ");
}
Catch (std: exception & e)
{
Std: cout <"Error:" <e. what () <endl;
Return-1;
}
Cout <"root length:" <root. size () <endl;
Int ita = pt. get <int> ("root. strage. id ");
String cattr = pt. get <string> ("root. strage. <xmlattr>. name ");
Cout <"root. strage. id:" <ita <"\ troot. strage. <xmlattr>. name:" <cattr <endl;
For (ptree: iterator itr = root. begin (); itr! = Root. end (); itr ++)
{
Ptree strage = itr-> second;
String ssv = strage. data ();
String sattr = strage. get <string> ("<xmlattr>. name ");
Int iattr = strage. get <int> ("<xmlattr>. alias ");
Float fattr = strage. get <float> ("<xmlattr>. classId ");
Boost: trim <string> (ssv); // remove leading and trailing Spaces
Cout <ssv <"[\ tname:" <sattr <"\ talias:" <iattr <"\ tclassid:" <fattr <endl;
For (int I = 0; I <3; I ++)
{
Ptree pt;
String str_value;
Try
{
Pt = strage. get_child (str_node_name [I]);
Str_value = pt. data ();
Cout <str_value <endl;
}
Catch (std: exception & e)
{
Cout <str_value <"parsing error:" <e. what () <endl;
Return-1;
}
Switch (I)
{
Case 0:
Xml_stage_detail.id = str_value;
Break;
Case 1:
Xml_stage_detail.name = str_value;
Break;
Case 2:
Xml_stage_detail.accout = str_value;
Break;
}
}
M_xml_detail-> push_back (xml_stage_detail );
}
Return 0;
}
Int main ()
{
Vector <xmlStageDetail> m_xml_detail;
Try
{
Load ("debug_settings.xml", & m_xml_detail );
Std: cout <"Success \ n ";
}
Catch (std: exception & e)
{
Std: cout <"Error:" <e. what () <endl;
Return-1;
}
Return 0;
}
The running result is as follows: