Tinyxml解析XML格式的檔案
一,理論補充
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;
}