首先下載tinyxml2 7.0.1庫:
https://github.com/leethomason/tinyxml2/releases
打開tinyxml2,然后升級sdk,解決方案->重定解決方案目標,升級。
然后編譯生成dll和庫文件,在tinyxml2\Debug-Dll下,將tinyxml2.lib和tinyxml2.dll拷貝到新建的工程目錄,在新建工程根目錄新建include文件夾,將tinyxml2.h拷入,並將工程->配置屬性->vc++目錄->包含目錄指向此目錄。
編碼:
#include "pch.h"
#include <iostream>
#include <tinyxml2.h>
#pragma comment(lib, "tinyxml2.lib")
using namespace std;
int main() {
static const char* xml =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
"<entries>"
"<entry name=\"My First Post\" age=\"52\">I believe every human has a finite number of heartbeats. I don't intend to waste any of mine</entry>"
"<entry name=\"The Second\" age=\"\">You know, being a test pilot isn't always the healthiest business in the world.</entry>"
"<entry>Entry</entry>"
"<entry name=\"The Third\" secretdata=\"9809832\">We have an infinite amount to learn both from nature and from each other</entry>"
"<entry name=\"Final Post...\" hidden=\"true\" age=\"3\">Across the sea of space, the stars are other suns.</entry>"
"</entries>";
tinyxml2::XMLDocument doc;
doc.Parse(xml);
tinyxml2::XMLHandle docHandle(&doc);
tinyxml2::XMLElement *entry = docHandle.FirstChildElement("entries").ToElement();
if (entry) {
for (tinyxml2::XMLNode *node = entry->FirstChildElement(); node; node = node->NextSibling()) {
tinyxml2::XMLElement *e = node->ToElement();
const char *name = e->Attribute("name");
if (name) cout << name << ": ";
cout << e->GetText();
int true_age = e->IntAttribute("age") + 50;
cout << " " << true_age << endl;
}
}
return 0;
}
如果需要單獨使用exe,需要注意帶上tinyxml2.dll文件
結果顯示: