Windows10 VS2017 C++ xml解析(tinyxml2库)

本文介绍如何使用TinyXML2库解析XML数据,包括库的下载、编译及在项目中集成步骤,通过示例代码展示如何读取XML元素和属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先下载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文件
结果显示:
在这里插入图片描述

参考文章:
https://gist.github.com/felton/5530029

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值