Posted on 2010-04-02 16:43
Condor 閱讀(1723)
評論(2) 編輯 收藏 引用
TinyXML有兩個不爽的地方,一是它的接口使用FILE*,另外一個是它對 wchar_t不能很好的支持。前陣子看Boost庫的更新中多了一個PropertyTree,他在處理XML時用到了另外一個小的庫 –RapidXML。既然間接的是Boost庫的一部分,所以是值得一試的。于是找到其官方網(wǎng)站(http://rapidxml.sourceforge.net/)研究了一番。一看之下,甚是滿意,也推薦給大家看看!
首先就是速度,據(jù)它自己宣稱比TinyXML快30到60倍,比Xerces DOM快50到100倍!詳細的測試比較請見其用戶手冊(http://rapidxml.sourceforge.net/manual.html)的“4. Performance ”一節(jié)。
其次它的設(shè)計非常的簡潔,只依賴于標準庫中的幾個基本的類。它的輸入輸出都是字符串,這樣很好,一個庫就應(yīng)該關(guān)注自己核心的內(nèi)容,做盡量少的事情。它的API其實和TinyXML倒是有幾分相似,用過TinyXML的人應(yīng)該很容易上手:
TinyXML主要接口類 RapidXML的主要接口類
TinyXML主要接口類
RapidXML的主要接口類
class TiXmlDocument
template<class Ch = char>
class xml_document
class TiXmlNode
template<class Ch = char>
class xml_node
class TiXmlAttribute
template<class Ch = char>
class xml_attribute
下面還是看一個具體的例子來體驗一下,下面是TinyXML官方教程中創(chuàng)建XML文檔的一段代碼:
void build_simple_doc( )
{
// Make xml: <?xml ..><Hello>World</Hello>
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實現(xiàn)類似功能的代碼:
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的樣例代碼:
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();
}
好東西,大家分享!:D