要讀的XML文件
示例代碼
#include <iostream>
#include "tinyxml2.h"
using namespace std;
using namespace tinyxml2;
/**************************************
<?xml version="1.0" encoding="UTF-8"?>
<!--this is a comment-->
<html>
<head>this is a heading!</head>
<body>
<p>this is a paragraph!</p>
<h1>this is first heading!</h1>
</body>
</html>
**************************************/
int main()
{
XMLDocument doc;
doc.LoadFile("myXML.xml");
auto htmlElement = doc.FirstChildElement("html");
auto headElement = htmlElement->FirstChildElement("head");
auto bodyElement = htmlElement->FirstChildElement("body");
auto pElement = bodyElement->FirstChildElement("p");
auto h1Element = bodyElement->FirstChildElement("h1");
cout<< headElement->GetText() << endl;
cout<< pElement->GetText() << endl;
cout<< h1Element->GetText() << endl;
return 0;
}
代碼解析
XMLDocument對象實例通過LoadFile()加載指定磁盤位置上的XML文件,XMLElement可通過FirstChildElement("元素名稱")找到掛載在該元素上的指定名稱的子元素(返回值是XMLElement),然後通過XMLElement的GetText()、QueryIntText()等一系列API即可獲取對應元素的內容。
運行結果