你不再需要TinyXML,推荐RapidXML

来源:互联网 发布:windows怎么录屏 编辑:程序博客网 时间:2024/04/19 14:06

目前我公司开发的Nexus Engine的底层对象序列化使用了TinyXML来读写XML文件。TinyXML有两个不爽的地方,一是它的接口使用FILE*,另外一个是它对wchar_t不能很好的支持。前阵子看Boost库的更新中多了一个PropertyTree,他在处理XML时用到了另外一个小的库--RapidXML。既然间接的是Boost库的一部分,所以是值得一试的。于是找到其官方网站(http://rapidxml.sourceforge.net/ )研究了一番。一看之下,甚是满意,也推荐给大家看看!

    首先就是速度,据它自己宣称比TinyXML快30到60倍 ,比Xerces DOM快50到100倍!详细的测试比较请见其用户手册(http://rapidxml.sourceforge.net/manual.html )的“4. Performance ”一节。

其次它的设计非常的简洁,只依赖于标准库中的几个基本的类。它的输入输出都是字符串,这样很好,一个库就应该关注自己核心的内容,做尽量少的事情。它的API其实和TinyXML倒是有几分相似,用过TinyXML的人应该很容易上手:

TinyXML主要接口类RapidXML的主要接口类class TiXmlDocument

template 
   class xml_document

class TiXmlNode

template 
    class xml_node

class TiXmlAttribute

template 
    class xml_attribute

下面还是看一个具体的例子来体验一下,下面是TinyXML官方教程中创建XML文档的一段代码:

view plaincopy to clipboardprint?
  1. void build_simple_doc( )  
  2. {  
  3.     // Make xml: World  
  4.     TiXmlDocument doc;  
  5.     TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0""""" );  
  6.     TiXmlElement * element = new TiXmlElement( "Hello" );  
  7.     TiXmlText * text = new TiXmlText( "World" );  
  8.     element->LinkEndChild( text );  
  9.     doc.LinkEndChild( decl );  
  10.     doc.LinkEndChild( element );  
  11.     doc.SaveFile( "madeByHand.xml" );  
  12. }  

 

下面是使用RapidXML实现类似功能的代码:

view plaincopy to clipboardprint?
  1. void build_simple_doc_by_rapidxml()  
  2. {  
  3.     xml_document<> doc;  
  4.     xml_node<>* decl = doc.allocate_node(node_declaration);  
  5.     xml_attribute<>* decl_ver =  
  6.         doc.allocate_attribute("version""1.0");  
  7.     decl->append_attribute(decl_ver);  
  8.     doc.append_node(decl);  
  9.     xml_node<>* node =  
  10.         doc.allocate_node(node_element,    "Hello""World");  
  11.     doc.append_node(node);  
  12.     string text;  
  13.     rapidxml::print(std::back_inserter(text), doc, 0);  
  14.     // write text to file by yourself  
  15. }  

下面是使用RapidXML分析XML的样例代码:

view plaincopy to clipboardprint?
  1. void parse_doc_by_rapidxml(char* xml_doc)  
  2. {  
  3.     xml_document<> doc;        // character type defaults to char  
  4.     doc.parse<0>(xml_doc);  // 0 means default parse flags  
  5.     xml_node<> *node = doc.first_node("Hello");  
  6.     string node_val = node->value();  
  7. }  

好东西,大家分享!:D