RapidXml使用方法

RapidXml使用方法一、写xml文件#include#include”rapidxml/rapidxml.hpp”#include”rapidxml/rapidxml_utils.hpp”#include”rapidxml/rapidxml_print.hpp”usingnamespacerapidxml;intmain(){ xml_document<>doc;

大家好,又见面了,我是你们的朋友全栈君。

一、写xml 文件

#include <iostream>
#include "rapidxml/rapidxml.hpp"
#include "rapidxml/rapidxml_utils.hpp"
#include "rapidxml/rapidxml_print.hpp"

using namespace rapidxml;

int main()
{    
	xml_document<> doc;  
	xml_node<>* rot = doc.allocate_node(rapidxml::node_pi,doc.allocate_string("xml version='1.0' encoding='utf-8'"));
	doc.append_node(rot);
	xml_node<>* node =   doc.allocate_node(node_element,"config","information");  
	xml_node<>* color =   doc.allocate_node(node_element,"color",NULL);  
	doc.append_node(node);
	node->append_node(color);
	color->append_node(doc.allocate_node(node_element,"red","0.1"));
	color->append_node(doc.allocate_node(node_element,"green","0.1"));
	color->append_node(doc.allocate_node(node_element,"blue","0.1"));
	color->append_node(doc.allocate_node(node_element,"alpha","1.0"));

	xml_node<>* size =   doc.allocate_node(node_element,"size",NULL); 
	size->append_node(doc.allocate_node(node_element,"x","640"));
	size->append_node(doc.allocate_node(node_element,"y","480"));
	node->append_node(size);

	xml_node<>* mode = doc.allocate_node(rapidxml::node_element,"mode","screen mode");
	mode->append_attribute(doc.allocate_attribute("fullscreen","false"));
	node->append_node(mode);

	std::string text;  
	rapidxml::print(std::back_inserter(text), doc, 0);  

	std::cout<<text<<std::endl; 

	std::ofstream out("config.xml");
	out << doc;

	system("PAUSE");
	return EXIT_SUCCESS;
}

生成的xml如下

  <?xml version="1.0" encoding="utf-8" ?> 
- <config>
- <color>
  <red>0.1</red> 
  <green>0.1</green> 
  <blue>0.1</blue> 
  <alpha>1.0</alpha> 
  </color>
- <size>
  <x>640</x> 
  <y>480</y> 
  </size>
  <mode fullscreen="false">screen mode</mode> 
  </config>

写文件例子2:

#include <string>
#include <iostream>
#include <fstream>
#include "rapidxml/rapidxml.hpp"
#include "rapidxml/rapidxml_utils.hpp"
#include "rapidxml/rapidxml_print.hpp"


using namespace rapidxml;
using namespace std;

int main(int argc, char* argv[])
{

    xml_document<> doc; //是解析器
    char a[] = "<top>"//如果单独传, 就不能加上xml的头部信息,
               //否则会报错
               "<name>tangqiang</name>"
               "<age>22</age>"
               "</top>";
    char* p = a;
    doc.parse<0>(p);

    xml_node<>* node = doc.first_node();//去顶级结点
    cout << (node->name())<< endl;
    node = node->first_node();
    while (node) {
        cout << node->name() << node->value() << endl;//name() value()返回的字符串不会去掉首尾的空白字符
        node = node->next_sibling();
    }

    ofstream out("test.xml");//ofstream 默认时,如果文件存在则会覆盖原来的内容,不存在则会新建
    out << doc;//doc 这样输出时在目标文件中不会有xml 头信息---<?xml version='1.0' encoding='utf-8' >
    out.close();
	system("pause");
    return 0;
}

生成的xml如下

<top>
	<name>tangqiang</name>
	<age>22</age>
</top>

二、读取xml文件

#include <iostream>
#include "rapidxml/rapidxml.hpp"
#include "rapidxml/rapidxml_utils.hpp"
#include "rapidxml/rapidxml_print.hpp"

using namespace rapidxml;

int main()
{
    file<> fdoc("config.xml");
    std::cout<<fdoc.data()<<std::endl;
    xml_document<>   doc;
    doc.parse<0>(fdoc.data());

    std::cout<<doc.name()<<std::endl;

    //! 获取根节点
    xml_node<>* root = doc.first_node();
    std::cout<<root->name()<<std::endl;

    //! 获取根节点第一个节点
    xml_node<>* node1 = root->first_node();
    std::cout<<node1->name()<<std::endl;

    xml_node<>* node11 = node1->first_node();
    std::cout<<node11->name()<<std::endl;
    std::cout<<node11->value()<<std::endl;

    //! 添加之后再次保存
    //需要说明的是rapidxml明显有一个bug
//那就是append_node(doc.allocate_node(node_element,"h","0"));的时候并不考虑该对象是否存在!
    xml_node<>* size = root->first_node("size");
    size->append_node(doc.allocate_node(node_element,"w","0"));
    size->append_node(doc.allocate_node(node_element,"h","0"));

    std::string text;
    rapidxml::print(std::back_inserter(text),doc,0);

    std::cout<<text<<std::endl;

    std::ofstream out("config.xml");
    out << doc;

    system("PAUSE");
    return EXIT_SUCCESS;
}

生成的xml为

<config>
	<color>
		<red>0.1</red>
		<green>0.1</green>
		<blue>0.1</blue>
		<alpha>1.0</alpha>
	</color>
	<size>
		<x>640</x>
		<y>480</y>
		<w>0</w>
		<h>0</h>
	</size>
	<mode fullscreen="false">screen mode</mode>
</config>

三、删除节点

#include "rapidxml/rapidxml.hpp"
#include "rapidxml/rapidxml_utils.hpp"
#include "rapidxml/rapidxml_print.hpp"

#include<iostream>
using namespace rapidxml;

int main()
{
	file<> fdoc("config.xml");
	xml_document<> doc;
	doc.parse<0>(fdoc.data());

	std::string text;  
	rapidxml::print(std::back_inserter(text), doc, 0);  
	std::cout<<text<<std::endl; 

	xml_node<>* root = doc.first_node();

	xml_node<>* sec = root->first_node();

	root->remove_node(sec); //移除根节点下的sec结点(包括该结点下所有结点)
	text="删除一个节点\r\n";  
	rapidxml::print(std::back_inserter(text), doc, 0);  
	std::cout<<text<<std::endl; 

	root->remove_all_nodes(); //移除根节点下所有结点
	text="删除所有节点\r\n";  
	rapidxml::print(std::back_inserter(text), doc, 0);  
	std::cout<<text<<std::endl; 

	std::ofstream out("test.xml");
	out<<doc;
	system("pause");
	return 0;
}

输出信息如下:

<config>
	<color>
		<red>0.1</red>
		<green>0.1</green>
		<blue>0.1</blue>
		<alpha>1.0</alpha>
	</color>
	<size>
		<x>640</x>
		<y>480</y>
		<w>0</w>
		<h>0</h>
	</size>
	<mode fullscreen="false">screen mode</mode>
</config>


删除一个节点

<config>
	<size>
		<x>640</x>
		<y>480</y>
		<w>0</w>
		<h>0</h>
	</size>
	<mode fullscreen="false">screen mode</mode>
</config>


删除所有节点

<config/>

四、编辑节点信息

暂时找到的编辑方法就是先删除再增加

#include "rapidxml/rapidxml.hpp"
#include "rapidxml/rapidxml_utils.hpp"
#include "rapidxml/rapidxml_print.hpp"

#include<iostream>
using namespace rapidxml;

int main()
{
	file<> fdoc("config.xml");
	std::cout<<fdoc.data()<<std::endl;
	xml_document<> doc;
	doc.parse<0>(fdoc.data());

	std::cout<<doc.name()<<std::endl;

	//! 获取根节点
	xml_node<>* root = doc.first_node();
	xml_node<>* delnode = root->first_node("color");
	root->remove_node(delnode);//先删除address节点
	//
	xml_node<>* lnode = root->first_node("size");//找到post节点
	xml_node<>* mynode=doc.allocate_node(node_element,"address","河北");
	root->insert_node(lnode,mynode);

	std::string text;
	rapidxml::print(std::back_inserter(text),doc,0);


	std::cout<<text<<std::endl;

	std::ofstream out("version.xml");
	out << doc;
	system("pause");
	return 0;   
}

输出如下:

<config>

	<color>

		<red>0.1</red>

		<green>0.1</green>

		<blue>0.1</blue>

		<alpha>1.0</alpha>

	</color>

	<size>

		<x>640</x>

		<y>480</y>

		<w>0</w>

		<h>0</h>

	</size>

	<mode fullscreen="false">screen mode</mode>

</config>





<config>
	<address>河北</address>
	<size>
		<x>640</x>
		<y>480</y>
		<w>0</w>
		<h>0</h>
	</size>
	<mode fullscreen="false">screen mode</mode>
</config>

五、遍历所有节点

for(rapidxml::xml_node<char> * node = parent_node->first_node("node name");
    node != NULL;
    node = node->next_sibling())
{
    ...
}

六、遍历所有属性

for(rapidxml::xml_attribute<char> * attr = node->first_attribute("node name");
    attr != NULL;
    attr = attr->next_attribute())
{
    char * value = attr->value();
}

七、gcc使用-std=gnu++0x 编译rapidxml时会报错,错误信息大概如下

…rapidxml_print.hpp:120:23: error:

call to function ‘print_element_node’ thatis neither visible in the

template definition nor found byargument-dependent lookup

out = print_element_node(out, node, flags,indent);

^

…rapidxml_print.hpp:242:22: note:

‘print_element_node’ should be declaredprior to the call site or in

namespace ‘rapidxml’

inline OutIt print_element_node(OutIt out,const xml_node<Ch> …

在这里找到了解决方法。

经查,原来print_node()函数被其他函数调用,但在却未定义(在被调用函数后定义了),所以解决方法为把print_node()函数移到print_children(), print_element_node() 等函数的后面。在原定义处就留一个函数声明就行。

具体diff文件如下。

Index: rapidxml_print.hpp
===================================================================
--- rapidxml_print.hpp	(revision 2025)
+++ rapidxml_print.hpp	(revision 2080)
@@ -101,68 +101,9 @@
 
         ///
         // Internal printing operations
-    
-        // Print node
+        
         template<class OutIt, class Ch>
-        inline OutIt print_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
-        {
-            // Print proper node type
-            switch (node->type())
-            {
-
-            // Document
-            case node_document:
-                out = print_children(out, node, flags, indent);
-                break;
-
-            // Element
-            case node_element:
-                out = print_element_node(out, node, flags, indent);
-                break;
-            
-            // Data
-            case node_data:
-                out = print_data_node(out, node, flags, indent);
-                break;
-            
-            // CDATA
-            case node_cdata:
-                out = print_cdata_node(out, node, flags, indent);
-                break;
-
-            // Declaration
-            case node_declaration:
-                out = print_declaration_node(out, node, flags, indent);
-                break;
-
-            // Comment
-            case node_comment:
-                out = print_comment_node(out, node, flags, indent);
-                break;
-            
-            // Doctype
-            case node_doctype:
-                out = print_doctype_node(out, node, flags, indent);
-                break;
-
-            // Pi
-            case node_pi:
-                out = print_pi_node(out, node, flags, indent);
-                break;
-
-                // Unknown
-            default:
-                assert(0);
-                break;
-            }
-            
-            // If indenting not disabled, add line break after node
-            if (!(flags & print_no_indenting))
-                *out = Ch('\n'), ++out;
-
-            // Return modified iterator
-            return out;
-        }
+        inline OutIt print_node(OutIt out, const xml_node<Ch> *node, int flags, int indent);        
         
         // Print children of the node                               
         template<class OutIt, class Ch>
@@ -372,7 +313,69 @@
             *out = Ch('>'), ++out;
             return out;
         }
+        
+        // Print node
+        template<class OutIt, class Ch>
+        inline OutIt print_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)
+        {
+            // Print proper node type
+            switch (node->type())
+            {
 
+            // Document
+            case node_document:
+                out = print_children(out, node, flags, indent);
+                break;
+
+            // Element
+            case node_element:
+                out = print_element_node(out, node, flags, indent);
+                break;
+            
+            // Data
+            case node_data:
+                out = print_data_node(out, node, flags, indent);
+                break;
+            
+            // CDATA
+            case node_cdata:
+                out = print_cdata_node(out, node, flags, indent);
+                break;
+
+            // Declaration
+            case node_declaration:
+                out = print_declaration_node(out, node, flags, indent);
+                break;
+
+            // Comment
+            case node_comment:
+                out = print_comment_node(out, node, flags, indent);
+                break;
+            
+            // Doctype
+            case node_doctype:
+                out = print_doctype_node(out, node, flags, indent);
+                break;
+
+            // Pi
+            case node_pi:
+                out = print_pi_node(out, node, flags, indent);
+                break;
+
+                // Unknown
+            default:
+                assert(0);
+                break;
+            }
+            
+            // If indenting not disabled, add line break after node
+            if (!(flags & print_no_indenting))
+                *out = Ch('\n'), ++out;
+
+            // Return modified iterator
+            return out;
+        }        
+
     }
     //! \endcond
 

八、判断解析能否成功

</pre><pre name="code" class="cpp">    try {
        doc.parse<0>((char*)tmpbuf);//会改变参数的内容,tmpbuf的生命周期必须到解析完
    } catch (rapidxml::parse_error &e) {
        err="parse xml error. ";
        err+=e.what();
		delete []tmpbuf;
		return s_stl_ruleinfo;
    }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/160881.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • TFS(Team Foundation Server)介绍和入门

    TFS(Team Foundation Server)介绍和入门

    2021年11月14日
    50
  • x201换风扇_「x201拆机」联想 Thinkpad x201i怎么拆机清理风扇灰尘? – seo实验室[通俗易懂]

    x201换风扇_「x201拆机」联想 Thinkpad x201i怎么拆机清理风扇灰尘? – seo实验室[通俗易懂]x201拆机笔记本散热风扇使用时间长了就累积很多灰尘,堵塞出风口,从而大幅降低散热效果。因此有必要对其清理。要彻底清理风扇灰尘,需要拆机方可。首先要把笔记本的电池取下。电池取下后,我们就可以开始拆卸内存了,首先要把内存外壳拆下。拆下内存盖后,我们只要把两边的卡扣松动,轻轻一拔即可把内存取下。这款笔记本的硬盘仓很隐蔽,不过在D面还是有明显的图标提示,拧下螺丝和卡扣,即可看到硬盘。硬盘盖拆下来之后,只…

    2022年6月27日
    124
  • 机器学习降维之主成分分析

    1.主成分基本思想主成分基本思想:在主成分分析中,首先对给定数据进行规范化,使得数据每一个变量的平均值维0,方差为1,之后对数据进行正交变换,原来由线性相关变量表示的数据,通过正交变换变成由若干个

    2021年12月30日
    45
  • httpclient4 请一定设置超时时间

    httpclient4 请一定设置超时时间httpclient4的设置方式和httpclient3有所不同,代码如下:HttpClienthttpclient=newDefaultHttpClient();httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,Config.20000);//连接时间20shttp

    2022年7月22日
    9
  • 关于astype的坑[通俗易懂]

    关于astype的坑[通俗易懂]也许对我来说是坑astype并不能inplace地改变一个ndarray。例如IN:arr=np.array([3.7,-1.2,-2.6,0.5,12.9,10.1])OUT:array([3.7,-1.2,-2.6,0.5,12.9,10.1])如果是直接输入:arr.astype(int32)然后检查arr.dtype,返回的是dtype(‘fl…

    2022年5月20日
    31
  • SuperGO外设下载地址安装,穿透模式使用

    SuperGO外设下载地址安装,穿透模式使用SuperGo下载地址安装使用教程这里给大家分五个步骤进行教学第一步:打开MM/纵行地图/SuperGo软件的下载网站www.tngps.com(用Safari浏览器进行操作),在APPstore下载并安装“TestFlight”软件,安装以后就不用管这个软件了第二步:下载完“TestFlight”后,返回刚才的网站点击“开始测试”,下载MM软件并安装。第三步:打开MM/纵行地图/SuperGo软件后插入设备,等待数秒等待软件连接成功后进入操作界面。第四步:在“搜索..

    2022年6月25日
    59

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号