C++中TinyXML读取xml文件用法详解

  #include

  //打开xml文件需要加载的头文件

  #include "tinystr.h"

  #include "tinyxml.h"

  #include

  #include

  using namespace std;

  int main()

  {

  //创建xml文件对象,并读取xml

  TiXmlDocument doc;

  doc.LoadFile("409.xml");

  //获取xml中根元素,并输出根节点的值,为

  TiXmlElement *root = doc.FirstChildElement();

  cout << root->Value() << endl;

  //获取根节点孩子,输出节点值,输出节点的内容,Text是char*

  TiXmlElement *child = root->FirstChildElement();

  cout << child->Value() << endl;

  cout << child->GetText() << endl;

  cout << strlen(child->GetText())<< endl;

  //cout <GetText()).name()<< endl;

  /*目标:找到xmin,xmax,ymin,ymax*/

  int xmin1,ymin1,xmax1,ymax1;

  //从根节点的第一个孩子节点开始遍历

  while(child!=NULL)

  {

  if(child->ValueTStr() == "object")

  {

  TiXmlElement *box = child->FirstChildElement();

  while(box->ValueTStr()!="bndbox")

  {

  box = box->NextSiblingElement();

  }

  TiXmlElement *xmin = box->FirstChildElement();

  xmin1 = atoi(xmin->GetText());

  //NextSiblingElement()获得同一层下一个节点

  TiXmlElement *ymin = xmin->NextSiblingElement();

  ymin1 = atoi(ymin->GetText());

  TiXmlElement *xmax = ymin->NextSiblingElement();

  xmax1 = atoi(xmax->GetText());

  TiXmlElement *ymax = xmax->NextSiblingElement();

  ymax1 = atoi(ymax->GetText());

  cout<

  cout<

  cout<

  cout<

  }

  child = child->NextSiblingElement();

  }

  /*

  cout<

  cout<

  cout<

  cout<

  */

  /*一些其他方法的测试*/

  /*

  //获取兄弟节点中的size节点

  TiXmlElement *brother = child->NextSiblingElement("size");

  cout << brother->Value() << endl;

  //cout << typeid(brother->GetText()).name()<< endl;

  //获取size节点下的属性值,<>中的属性,本例没有属性

  //cout <Attribute("width")<

  //找size下面节点width

  TiXmlElement *brother_child = brother->FirstChildElement();

  cout << brother_child->Value() << endl;

  cout << brother_child->GetText() << endl;

  //读取到内容,并转为int型,因为项目需要int数据

  int width = atoi(brother_child->GetText());

  cout << width << endl;

  */

  return 0;

  }