网上下载tinyxml2:tinyxml2.h和tinyxml2.cpp
加载xml
1 XMLDocument doc; 2 doc.LoadFile("test.xml"); 3 const char* content= doc.FirstChildElement( "Hello" )->GetText(); 4 printf( "Hello,%s", content );
解析xml
1 <?xml version="1.0"?> 2 <scene name="Depth"> 3 <node type="camera"> 4 <eye>0 10 10</eye> 5 <front>0 0 -1</front> 6 <refUp>0 1 0</refUp> 7 <fov>90</fov> 8 </node> 9 <node type="Sphere"> 10 <center>0 10 -10</center> 11 <radius>10</radius> 12 </node> 13 <node type="Plane"> 14 <direction>0 10 -10</direction> 15 <distance>10</distance> 16 </node> 17 </scene> 18 19 20 #include <iostream> 21 #include"tinyxml2.h" 22 using namespace std; 23 using namespace tinyxml2; 24 void example2() 25 { 26 XMLDocument doc; 27 doc.LoadFile("test.xml"); 28 XMLElement *scene=doc.RootElement(); 29 XMLElement *surface=scene->FirstChildElement("node"); 30 while (surface) 31 { 32 XMLElement *surfaceChild=surface->FirstChildElement(); 33 const char* content; 34 const XMLAttribute *attributeOfSurface = surface->FirstAttribute(); 35 cout<< attributeOfSurface->Name() << ":" << attributeOfSurface->Value() << endl; 36 while(surfaceChild) 37 { 38 content=surfaceChild->GetText(); 39 surfaceChild=surfaceChild->NextSiblingElement(); 40 cout<<content<<endl; 41 } 42 surface=surface->NextSiblingElement(); 43 } 44 } 45 int main() 46 { 47 example1(); 48 return 0; 49 }
保存xml
1 void CConfig::SaveToFile() 2 { 3 tinyxml2::XMLDocument doc; 4 std::stringstream ss; 5 ss << "<?xml version="1.0" encoding="UTF-8" ?>" 6 << "<Database>" 7 << "</Database>"; 8 doc.Parse(ss.str().c_str()); 9 string strXml(DPC::GetAppPath()); 10 strXml += "\SiteCenter.xml"; 11 doc.SaveFile(strXml.c_str()); 12 }