使用pugi解析XML(简单示例)

项目要求使用pugi解析xml,本文介绍了pugi的相关内容。它是c++下轻量化、简单、快速的xml解析工具,上手难度低。给出了下载网址,将src内特定文件放入工程即可使用,还展示了解析xml简单字符串和简单文件的示例。

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

项目中建议(要求)使用pugi解析xml,那么今天就来学习一下pugi。

  1. 下载
    下载网址:https://pugixml.org

  2. 使用方式:
    官网介绍第一句称自己为轻量化、简单、快速的c++下xml解析工具,实际使用上手难度确实低。
    将src内的pugiconfig.hpp、pugixml.cpp、pugixml.hpp放入工程中,就可以使用了,就是这么简单。

  3. 简单示例:pugi解析xml简单字符串
    这是一个超简单示例:

#include <iostream>
#include "pugiconfig.hpp"
#include "pugixml.hpp"
#include <string>
using namespace std;

int main()
{
	char xmlStr[1024] = "<?xml version=\"1.0\"?>\r\n"
		"<Response>\r\n"
		"<CmdType>DeviceInfo</CmdType>\r\n"
		"<SN>17430</SN>\r\n"
		"<DeviceID>102934857689237</DeviceID>\r\n"
		"<Manufacturer>Happtimesoft</Manufacturer>\r\n"
		"<Model>HTIPC</Model>\r\n"
		"</Response>\r\n";
	pugi::xml_document doc;
	doc.load_string(xmlStr);
	pugi::xml_node response = doc.child("Response");
	//遍历
	for (pugi::xml_node node = response.first_child(); node != nullptr; node = node.next_sibling())
	{
		//cout << node.child_value() << endl; //两种访问方式
		cout << node.name() << ": " << node.text().as_string() << endl;
	}
	//特定访问
	pugi::xml_node sn = response.child("SN");
	cout << "SN: " << sn.child_value() << endl;
	system("pause");
	return 0;
}
  1. 简单示例:pugi解析简单xml文件
    xml文件内容:
<?xml version="1.0"?>
		<Response>
		<CmdType>DeviceInfo</CmdType>
		<SN>17430</SN>
		<DeviceID>102934857689237</DeviceID>
		<Manufacturer>Happtimesoft</Manufacturer>
		<Model>HTIPC</Model>
		</Response>

代码:(和上面的代码简直一毛一样)

#include <iostream>
#include "pugiconfig.hpp"
#include "pugixml.hpp"
#include <string>
using namespace std;

int main()
{

	pugi::xml_document doc;
	doc.load_file("test.xml");
	pugi::xml_node response = doc.child("Response");

	//遍历
	for (pugi::xml_node node = response.first_child(); node != nullptr; node = node.next_sibling())
	{
		//cout << node.child_value() << endl; //两种访问方式
		cout <<  node.name() << ": " << node.text().as_string() << endl;
	}

	//特定访问
	pugi::xml_node sn = response.child("SN");
	cout << "SN: " << sn.child_value() << endl;

	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值