RapidXml的使用
RapidXml Manual:?http://rapidxml.sourceforge.net/manual.html
DOM解析是將XML文件全部載入,組裝成一顆DOM樹,然后通過節點以及節點之間的關系來解析XML文件。
RapidXml是一個使用C++編寫的XML DOM解析工具包,整個解析工具包包含在一個頭文件中,所以使用時不用編譯也不用連接。只要包含rapidxml中的三個頭文件即可。
RapidXml 試圖成為最快的 XML DOM 解析工具包,同時保證解析結果的可用性、可移植性以及與 W3C 標準的兼容性。在操作同一數據時,其解析速度接近于 strlen() 函數。
- 解析:
以下代碼使用RapidXml解析一段以0結束的字符串text:
1 using namespace rapidxml; 2 xml_document<> doc; // character type defaults to char 3 doc.parse<0>(text); // 0 means default parse flags其中,doc為解析得到的DOM tree的根節點。由于所有的RapidXml接口都包含在rapixml,所以用戶需要使用這個名字空間。類xml_document代表了DOM結構的根,它公開繼承了xml_node和memory_pool。xml_document::parse()的模板參數用來標識解析標志,使用它可以對解析器的行為進行調整(這里我也不太明白,調整什么?)。這個標志必須是編譯時的常數。
- Accessing?DOM Tree:
使用xml_node和xml_attribute類中的方法訪問DOM tree。
1 cout << "Name of my first node is: " << doc.first_node()->name() << "\n"; 2 xml_node<> *node = doc.first_node("foobar"); 3 cout << "Node foobar has value " << node->value() << "\n"; 4 for (xml_attribute<> *attr = node->first_attribute(); 5 attr; attr = attr->next_attribute()) 6 { 7 cout << "Node foobar has attribute " << attr->name() << " "; 8 cout << "with value " << attr->value() << "\n"; 9 }- Modifying DOM Tree:
下例為創建一個HTML文檔,它唯一的內容是一個google.com的鏈接(?<a href=google.com>Google</a>):
xml_document<> doc; xml_node<> *node = doc.allocate_node(node_element, "a", "Google"); doc.append_node(node); xml_attribute<> *attr = doc.allocate_attribute("href", "google.com"); node->append_attribute(attr);nodes和attributes并不真正擁有文章中節點和屬性的名字及值,因為它們只是存儲了指向源文中某個位置的指針。所以,當為一個節點分配名字和值的時候,必須確保待這些字符串有合適的生命周期。最簡單的方法是從xml_document memory pool中分配字符串。當然,在上面例子中沒有必要這么做,因為這里使用了字符常量。下面的代碼使用了memory_pool::allocate_string()方法分配節點名字(這樣它將和文檔具有相同的生命周期)給新的節點:
xml_document<> doc; char *node_name = doc.allocate_string(name); // Allocate string and copy name into it xml_node<> *node = doc.allocate_node(node_element, node_name); // Set node name to node_name- Printing XML
?將xml_document和xml_node的對象寫入一XML的string里,可以使用在rapidxml_print.hpp頭文件中定義的print()函數或者操作符<<。
using namespace rapidxml; xml_document<> doc; // character type defaults to char // ... some code to fill the document// Print to stream using operator << std::cout << doc; // Print to stream using print function, specifying printing flags print(std::cout, doc, 0); // 0 means default printing flags// Print to string using output iterator std::string s; print(std::back_inserter(s), doc, 0);// Print to memory buffer using output iterator char buffer[4096]; // You are responsible for making the buffer large enough! char *end = print(buffer, doc, 0); // end contains pointer to character after last printed character *end = 0; // Add string terminator after XML?
?
轉載于:https://www.cnblogs.com/hihilary/archive/2012/11/18/2772983.html
總結
以上是生活随笔為你收集整理的RapidXml的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: JavaScript特效——让文字每秒钟
- 下一篇: JDK1.6官方下载_JDK6官方下载
