c++ pugixml 插入节点和设置属性例子

本文介绍如何利用Pugixml库在C++中解析和操作XML文件,包括加载字符串到XML文档、添加声明节点、插入子节点、设置属性和值、打印文档以及保存到文件。

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

#include "stdafx.h"
#include "pugixml1.9/pugixml.hpp"
#include <iostream>

/*
	test.xml格式

<?xml version="1.0" encoding="utf-8"?>
<Root ErrCode="0" Status="OK">
	<child01 yes="1">01</child01>
</Root>

*/
int _tmain(int argc, _TCHAR* argv[])
{
	std::string xmlTmp = "<Root ErrCode='0' Status='OK'></Root>";
	//1、内存中
	pugi::xml_document doc;
	pugi::xml_parse_result ret = doc.load_string(xmlTmp.c_str());
	if (ret.status != pugi::status_ok)
	{
		return -1;
	}

	pugi::xml_node xdec = doc.prepend_child(pugi::node_declaration);
	xdec.append_attribute("version").set_value("1.0");
	xdec.append_attribute("encoding").set_value("utf-8");

	//2、读取xmlTmp中节点
	pugi::xpath_node xRoot = doc.select_node("//Root");//单root
	pugi::xml_node hxRoot01= xRoot.node(); 
	

	//3、在root 插入子节点 并设置属性
	pugi::xml_object_range<pugi::xml_node_iterator> child01 = hxRoot01.children();

	//插入节点child01 
	pugi::xml_node childNode = hxRoot01.append_child("child01");
	childNode.text().set("01"); //设置值

	//【childNode】设置属性
	pugi::xml_attribute attributeTmp = childNode.append_attribute("yes");
	attributeTmp.set_value("1");
	
	//4、打印
	doc.print(std::cout);

	//5、保存
	doc.save_file("test.xml");

	return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值