1. 簡介
TinyXML2(最新版本)是一個開源的功能齊全的XML解析庫 For C++,源碼見:github。
2. 開始使用
首先從Github上獲得源碼,是一個完整的演示工程,我們只需要其中的tinyxml2.cpp
和tinyxml2.h
,將這兩個文件拷貝到新建的VS工程目錄下,然后就可以開始使用了,這是方法之一,也可以將源碼編譯為.lib
然后鏈接到工程中。
然后包含頭文件tinyxml2.h
,並使用命名空間:using namespace tinyxml2
3. 寫XML
#include <iostream>
#include "tinyxml2.h"
using namespace std;
using namespace tinyxml2;
int main()
{
// 新建一個空文檔(表示完整的xml)
XMLDocument xmlDoc;
// 新節點
XMLNode * pRoot = xmlDoc.NewElement("Root");
// 插入到xmlDoc的第一個節點(根節點)
xmlDoc.InsertFirstChild(pRoot);
// 新建一個元素
XMLElement *pElement = xmlDoc.NewElement("IntValue");
// 設置該元素(節點)的值
pElement->SetText(10);
// 設置該元素的屬性(重載)
pElement->SetAttribute("year", 2017);
pElement->SetAttribute("key", "hello");
// 將該節點添加到pRoot節點下("Root")
pRoot->InsertEndChild(pElement);
// 指向新的節點
pElement = xmlDoc.NewElement("FloatValue");
// 添加到pRoot節點(依次向下添加)
pRoot->InsertEndChild(pElement);
// 新建一個節點
XMLElement *pNewElement = xmlDoc.NewElement("value1");
// 設置節點的值
pNewElement->SetText(1.0);
// 將該節點添加到pElement節點下("FloatValue")
pElement->InsertFirstChild(pNewElement);
// 指向新的節點
pNewElement = xmlDoc.NewElement("value2");
// 設置節點的值
pNewElement->SetText(2.0);
// 將該節點插入到pElement節點下(依次向下添加)
pElement->InsertEndChild(pNewElement);
// 保存文件
XMLError eResult = xmlDoc.SaveFile("test.xml");
if (eResult != XML_SUCCESS)
cout << "error\n";
return 0;
}
結果 test.xml
<Root>
<IntValue year="2017" key="hello">10</IntValue>
<FloatValue>
<value1>1</value1>
<value2>2</value2>
</FloatValue>
</Root>
4. 讀取XML
#include <iostream>
#include "tinyxml2.h"
using namespace std;
using namespace tinyxml2;
int main()
{
// 新建一個空文檔
XMLDocument xmlDoc;
// 讀取指定的xml文件並判斷讀取是否成功
XMLError eResult = xmlDoc.LoadFile("test.xml");
if (eResult != XML_SUCCESS)
{
cout << "error\n";
return XML_ERROR_FILE_NOT_FOUND;
}
// 獲得該文件的第一個節點(根節點)
XMLNode * pRoot = xmlDoc.FirstChild();
if (pRoot == nullptr)
return XML_ERROR_FILE_READ_ERROR;
// 找到該節點中的名字為 "IntValue"的第一個子節點
XMLElement * pElement = pRoot->FirstChildElement("IntValue");
if (pElement == nullptr)
return XML_ERROR_PARSING_ELEMENT;
// 讀取子節點的值
int iOutInt;
eResult = pElement->QueryIntText(&iOutInt);
if (eResult != XML_SUCCESS)
return XML_ERROR_PARSING;
else
cout << iOutInt << endl;
// 讀取子節點的屬性
int iOutYear;
eResult = pElement->QueryIntAttribute("year", &iOutYear);
if (eResult != XML_SUCCESS)
return XML_ERROR_PARSING;
else
cout << iOutYear << endl;
// 獲得該子節點的下一個兄弟節點(更深層的節點搜索類似)
XMLElement * nextNode = pElement->NextSiblingElement();
cout << nextNode->Name() << endl;
return 0;
}
運行結果
10
2017
FloatValue