XML解析之 Pugixml下载导入及使用介绍

下载:官方链接

箭头部分是github的源码,圈住部分有讲解

下载完成后,解压,找到src文件夹,里面有三个文件,分别是一个cpp文件:pugixml.cpp,和两个头文件:pugiconfig.hpp,pugixml.hpp,这三个文件就是我们要用到的(用的的时候把三个文件拽到你的工程文件夹,并在编译器上添加

编译,你可能会遇到一些error:例如: error(点击)

解决之后再编译,成功,这时你已经可以使用pugixml进行xml解析了。

使用:

首先:在你的cpp文件中包含这个头文件:#include “pugixml.hpp”  

读取XML中内容:

例如读取这样一个XML文件,并把读取的内容打印在ListControl控件的表格中:

<stock>
	<data item="30342">
		<item>
			<pugixml>hello</pugixml>
		</item>
		<item>
			<pugixml>world</pugixml>
		</item>
		<item>
			<pugixml>hello world</pugixml>
		</item>
    </data>
<stock>

其中m_List是ListControl控件绑定的Control类型的变量


	pugi::xml_document doc;
	//加载xml文件;
	if (!doc.load_file(TEXT("stock.xml")));
	{return 0;}

	//获取XML文件中stock结点中的data结点
	pugi::xml_node DataNode= doc.child("stock").child("data");

        //获取data结点的item属性值30342;
	CString Att_Data= DataNode.attribute("item").value();

        m_List.InsertItem(0,"");  //表格插入一行,位置为0;
        int col = 0; //列

	//获取XML文件中data结点中的所有item结点
	
	//遍历data结点下的所有item结点;
	for (pugi::xml_node ItemNode=DataNode.first_child();ItemNode;ItemNode= ItemNode.next_sibling())
	{
        //获取每一个item节点的第一个子节点的text
           m_List.SetItemText(0,col,ItemNode.first_child().text().as_string()); 
            col++;
        
	}


pugixml具体的方法可以去官方文档查看:https://pugixml.org/docs/manual.html

向XML写入内容:

	//创建xml_document;
	pugi::xml_document Mydoc;
	//插入declaration;
	pugi::xml_node decl = Mydoc.append_child(pugi::node_declaration);
	decl.append_attribute("version")="2.0";
	//并列插入Message结点;
	pugi::xml_node Message = Mydoc.append_child("Message");
	//在Message结点下面插入date结点;
	pugi::xml_node date = Message.append_child("date");
	date.append_child(pugi::node_pcdata).set_value("2019/10/14");//在结点间插入文本信息
	//在message下面插入Params结点;
	pugi::xml_node Params = Message.append_child("Params");
	//在Params下面插入param结点;
	pugi::xml_node Param1 = Params.append_child("Param");
	Param1.append_attribute("name")="proname";//append_attribute表示插入属性;
	Param1.append_attribute("type")= "string";
	Param1.append_attribute("value")= "P";
	pugi::xml_node name1 = Param1.append_child("name1");
	name1.append_child(pugi::node_pcdata).set_value("shan");//node_pcdata表示写入xml中的为文本信息;
	//保存文件
	Mydocument.save_file("自定义路径+\\Message.xml");

结果:

            在这里插入图片描述

发布了114 篇原创文章 · 获赞 120 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/alzzw/article/details/103478568
今日推荐