Tinyxml解析XML格式的文件

来源:互联网 发布:c语言 algin 编辑:程序博客网 时间:2024/05/30 04:40


一,理论补充

1,xml是一种数据格式

2,本文的xml文档放在了D盘下面

3,Tinyxml解析库包括2个.h文件,4个.cpp文件

4,引用Tinyxml库文件用“”

5,本文是读取xml数据,并打印xml数据的 操作

6,如果没有基本的C++知识,不建议阅读本文

7,本文参考了 网上的代码,并做了一些改动,更详细的介绍后续给出,也欢迎大家批评指正

二,代码范例

#include <iostream>
#include <string>
#include "tinyxml.h"
#include <conio.h>
 // using std::string;
using namespace::std;
 int main()
{

 
    const char * xmlFile = "D:\\Students.xml";
    TiXmlDocument doc;                             
    if (doc.LoadFile(xmlFile)) {
        doc.Print();
    } else {
        cout << "can not parse xml conf/school.xml" << endl;
    
    }


  TiXmlDocument* myDocument = new TiXmlDocument();
  myDocument->LoadFile("D:\\Students.xml");
  TiXmlElement* rootElement = myDocument->RootElement();  //Class
  TiXmlElement* studentsElement = rootElement->FirstChildElement();  //Students
  TiXmlElement* studentElement = studentsElement->FirstChildElement();  //Students

   TiXmlAttribute* attributeOfrootElement = rootElement->FirstAttribute();  //获得student的na
    std::cout << attributeOfrootElement->Name() << " : " << attributeOfrootElement->Value() << endl;

  while ( studentElement )
  {
    TiXmlAttribute* attributeOfStudent = studentElement->FirstAttribute();  //获得student的name属性
    while ( attributeOfStudent )
 {
      std::cout << attributeOfStudent->Name() << " : " << attributeOfStudent->Value() << std::endl;
 
   attributeOfStudent = attributeOfStudent->Next();
    }
    TiXmlElement* phoneElement = studentElement->FirstChildElement();//获得student的phone元素
    std::cout << "phone" << " : " << phoneElement->GetText() << std::endl;

 TiXmlElement* studentNoElement = studentElement->FirstChildElement();//获得student的phone元素
    std::cout << "phone" << " : " << studentNoElement->GetText() << std::endl;


    TiXmlElement* addressElement = phoneElement->NextSiblingElement();
    std::cout << "address" << " : " << phoneElement->GetText() << std::endl;
    studentElement = studentElement->NextSiblingElement();
  }
  getch();
  return 0;
}

0 0
原创粉丝点击