pugixml库学习之添加节点

作者:朱金灿

来源:http://blog.csdn.net/clever101

 

           继续学习pugixml库使用。xml文件的节点一般有两种方式:

            <paramname="version" type="float" value="1.1" />和

                        <Welcome>Welcometo MyApp</Welcome>

 

            今天我们学习如何使用pugixml库给一个xml文件添加这两种节点。

        xml的原文件是:

<?xml version="1.0"?>
<MyApp>
	<Messages>
		<Welcome>Welcome to MyApp</Welcome>
		<Farewell>Thank you for using MyApp</Farewell>
	</Messages>
	<Windows>
		<Window name="MainFrame" x="5" y="15" w="400" h="250" />
	</Windows>
</MyApp>

           我们要达到的效果是:

<?xml version="1.0"?>
<MyApp>
	<Messages>
		<Welcome>Welcome to MyApp</Welcome>
		<Farewell>Thank you for using MyApp</Farewell>
	</Messages>
	<Windows>
		<Window name="MainFrame" x="5" y="15" w="400" h="250" />
		<param name="version" type="float" value="1.1" />
		<Welcome>Welcome to MyApp</Welcome>
		<param name="version" type="float" value="1.1" />
		<Farewell>Thank you for using MyApp</Farewell>
	</Windows>
</MyApp>

              实现代码如下,代码较为简单,这里就不作详细解释了:

#include <vector>
#include <string>
#include <pugixml.hpp>


int _tmain(int argc, _TCHAR* argv[])
{
    pugi::xml_document doc;
	// 加载xml文件
	pugi::xml_parse_result ret = doc.load_file(_T("E:\\ConfigDemo.xml"));

	pugi::xml_node Messages = doc.child(_T("MyApp")).child(_T("Messages"));
	std::vector<std::pair<std::string,std::string> > vecNode;

	// 读取原有的Welcome 节点和Farewell节点,并保存其值
	for (pugi::xml_node Plugin = Messages.first_child(); Plugin; Plugin = Plugin.next_sibling())
	{
		typedef std::pair<std::string,std::string> string_Pair;
        std::string strNodeName = Plugin.name();
        std::string strValue = Messages.child_value(strNodeName.c_str());
		vecNode.push_back(string_Pair(strNodeName,strValue));
	}

    pugi::xml_node window = doc.child(_T("MyApp")).child(_T("Windows"));
	for (int i =0;i<vecNode.size();i++)
	{
		// 添加Welcome 节点和Farewell节点
	    pugi::xml_node new_node = window.append_child(vecNode[i].first.c_str());

		new_node.append_child(pugi::node_pcdata).set_value(vecNode[i].second.c_str());
		// 添加param 节点
		pugi::xml_node param = window.insert_child_before("param",new_node);
		param.append_attribute("name") = "version";
		param.append_attribute("value") = 1.1;
		param.insert_attribute_after("type", param.attribute("name")) = "float";
	}

	doc.save_file(_T("E:\\ConfigDemo.xml"));
	getchar();
	return 0;
}








  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

clever101

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值