目前我公司開(kāi)發(fā)的NexusEngine的底層對象序列化使用了TinyXML來(lái)讀寫(xiě)XML文件。TinyXML有兩個(gè)不爽的地方,一是它的接口使用FILE*,另外一個(gè)是它對wchar_t不能很好的支持。前陣子看Boost庫的更新中多了一個(gè)PropertyTree,他在處理XML時(shí)用到了另外一個(gè)小的庫--RapidXML。既然間接的是Boost庫的一部分,所以是值得一試的。于是找到其官方網(wǎng)站(
http://rapidxml.sourceforge.net/)研究了一番。一看之下,甚是滿(mǎn)意,也推薦給大家看看!
首先就是速度,據它自己宣稱(chēng) 比TinyXML快30到60倍,比Xerces DOM快50到100倍!詳細的測試比較請見(jiàn)其用戶(hù)手冊(
http://rapidxml.sourceforge.net/manual.html)的“4. Performance ”一節。
其次它的設計非常的簡(jiǎn)潔,只依賴(lài)于標準庫中的幾個(gè)基本的類(lèi)。它的輸入輸出都是字符串,這樣很好,一個(gè)庫就應該關(guān)注自己核心的內容,做盡量少的事情。它的API其實(shí)和TinyXML倒是有幾分相似,用過(guò)TinyXML的人應該很容易上手:
TinyXML主要接口類(lèi) RapidXML的主要接口類(lèi)
class TiXmlDocument
template
class xml_document
class TiXmlNode
template
class xml_node
class TiXmlAttribute
template
class xml_attribute
下面還是看一個(gè)具體的例子來(lái)體驗一下,下面是TinyXML官方教程中創(chuàng )建XML文檔的一段代碼:
view plaincopy to clipboardprint?void build_simple_doc( )
{
// Make xml: World
TiXmlDocument doc;
TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "", "" );
TiXmlElement * element = new TiXmlElement( "Hello" );
TiXmlText * text = new TiXmlText( "World" );
element->LinkEndChild( text );
doc.LinkEndChild( decl );
doc.LinkEndChild( element );
doc.SaveFile( "madeByHand.xml" );
}
下面是使用RapidXML實(shí)現類(lèi)似功能的代碼:
view plaincopy to clipboardprint?void build_simple_doc_by_rapidxml()
{
xml_document<> doc;
xml_node<>* decl = doc.allocate_node(node_declaration);
xml_attribute<>* decl_ver =
doc.allocate_attribute("version", "1.0");
decl->append_attribute(decl_ver);
doc.append_node(decl);
xml_node<>* node =
doc.allocate_node(node_element, "Hello", "World");
doc.append_node(node);
string text;
rapidxml::print(std::back_inserter(text), doc, 0);
// write text to file by yourself
}
下面是使用RapidXML分析XML的樣例代碼:
view plaincopy to clipboardprint?void parse_doc_by_rapidxml(char* xml_doc)
{
xml_document<> doc; // character type defaults to char
doc.parse<0>(xml_doc); // 0 means default parse flags
xml_node<> *node = doc.first_node("Hello");
string node_val = node->value();
}