使用tinyxml2库解析xml
生活随笔
收集整理的這篇文章主要介紹了
使用tinyxml2库解析xml
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
tinyxml2簡介
tinyxml2是c++編寫的輕量級的xml解析器,而且是開放源代碼的,在一些開源的游戲引擎中用的比較多。源碼托管在github上。
源碼地址:https://github.com/leethomason/tinyxml2
tinyxml2使用起來非常簡單,下載源碼后無需編譯成lib文件,直接將tinyxml2.h和tinyxml2.cpp兩個文件添加到你自己的工程中即可。
tinyxml2使用
我們現在有一個persons.xml文件,里面存放著一些人員信息,內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person name="張三">
<sex>男</sex>
<age>30</age>
</person>
<person name="花花">
<sex>女</sex>
<age>20</age>
</person>
</persons>
現在我們使用tinyxml2庫遍歷該xml文件,獲取姓名為”花花“的人員的全部信息。
代碼如下:
#include "stdafx.h"
#include <string>
#include <iostream>
#include "tinyxml2.h"
#define String std::string
using namespace tinyxml2;
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
/*
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person name="張三">
<sex>男</sex>
<age>30</age>
</person>
<person name="花花">
<sex>女</sex>
<age>20</age>
</person>
</persons>
*/
//通過遍歷輸出姓名為“花花”的個人信息
XMLDocument* doc = new XMLDocument();
if(doc->LoadFile("persons.xml") != XML_NO_ERROR)
{
cout<<"read file error!"<<endl;
return -1;
}
//獲取根節點,即persons節點
XMLElement* root = doc->RootElement();
XMLElement* person = root->FirstChildElement("person");
while (person)
{
//獲取person的name屬性
const XMLAttribute * nameAttr = person->FirstAttribute();
String perName = nameAttr->Value();
if(perName == "花花")
{
cout<<nameAttr->Name()<<":"<<nameAttr->Value()<<endl;
//遍歷person的其他子節點
XMLElement * perAttr = person->FirstChildElement();
while(perAttr)
{
cout<<perAttr->Name()<<":"<<perAttr->GetText()<<endl;
perAttr = perAttr->NextSiblingElement();
}
}
person = person->NextSiblingElement();
}
delete doc;
system("pause");
}
tinyxml2采用DOM(文檔對象模型)方式處理xml文件,xml文件中的每一種元素都有對應的類。
doc->LoadFile("persons.xml")
XMLDocument類的對象代表一份xml文檔實例,調用LoadFile方法與xml文件綁定。
XMLElement* root = doc->RootElement();
XMLElement* person = root->FirstChildElement("person");
我們通過XMLDocument類的RootElement獲取根節點(xml文件的根節點只有一個),通過root->FirstChildElement(“person”)獲取元素名為person的第一個子節點。有了該節點調用XMLElement類NextSiblingElement()方法不斷循環遍歷即可。
運行效果
可以看到我們需要的信息打印了出來。
總結
以上是生活随笔為你收集整理的使用tinyxml2库解析xml的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 水炮的作战要求有哪些
- 下一篇: 军人烈士家属能免物业费吗