http://www.cnblogs.com/xudong-bupt/p/3733306.html
要点:部分的函数接口不支持string类型,支持的是char* 类型的,所以要进行类型的转换,str.c_str()转化成c版本的string。 读取VOC的标记文件代码: #include <iostream> #include <string> #include <fstream> #include "tinyxml.h" //#include<time.h> using namespace std; //using namespace cv; //读取VOC格式的xml文件 int readDemoXml(string fileName) { TiXmlDocument doc; if(!doc.LoadFile(fileName.c_str())) { cerr << doc.ErrorDesc() << endl; return -1; } TiXmlElement* root = doc.FirstChildElement(); if(root == NULL) { cerr << "Failed to load file: No root element." << endl; doc.Clear(); return -1; } cout<<root->Value()<<endl;//根节点 for(TiXmlElement* elem = root->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement()) { //string elemName = elem->Value(); cout<<" "<<elem->Value(); if(elem->FirstChildElement())//嵌套有子节点 { cout<<endl; for (TiXmlElement* childelem=elem->FirstChildElement();childelem!=NULL;childelem=childelem->NextSiblingElement()) { cout<<" "<<childelem->Value(); if(childelem->FirstChildElement())//子节点中还有子节点 { cout<<endl; for (TiXmlElement* grandelem=childelem->FirstChildElement();grandelem!=NULL;grandelem=grandelem->NextSiblingElement()) { cout<<" "<<grandelem->Value()<<": "<<grandelem->FirstChild()->ToText()->Value()<<endl; } } else { cout<<": "<<childelem->FirstChild()->ToText()->Value()<<endl; } } } else { cout<<": "<<elem->FirstChild()->ToText()->Value()<<endl; } /*if (strcmp(elemName.c_str(),"folder")==0) { cout<<"结点的值:"<<elem->FirstChild()->ToText()->Value()<<endl; }*/ } doc.Clear(); return 0; } int main() { string fileName="F:/VOC2007/Annotations/demo1.xml"; readDemoXml(fileName); system("pause"); return 0; }
XML文件内容
<annotation> <folder>VOC2007</folder> <filename>000001.jpg</filename> <source> <database>The VOC2007 Database</database> <annotation>PASCAL VOC2007</annotation> <image>flickr</image> <flickrid>341012865</flickrid> </source> <owner> <flickrid>Fried Camels</flickrid> <name>Jinky the Fruit Bat</name> </owner> <size> <width>353</width> <height>500</height> <depth>3</depth> </size> <segmented>0</segmented> <object> <name>dog</name> <pose>Left</pose> <truncated>1</truncated> <difficult>0</difficult> <bndbox> <xmin>48</xmin> <ymin>240</ymin> <xmax>195</xmax> <ymax>371</ymax> </bndbox> </object> <object> <name>person</name> <pose>Left</pose> <truncated>1</truncated> <difficult>0</difficult> <bndbox> <xmin>8</xmin> <ymin>12</ymin> <xmax>352</xmax> <ymax>498</ymax> </bndbox> </object> </annotation>解析结果