libxml++庫 (2) Node, contentNode and Element 比較

libxml庫中Node, contentNode還有Element的概念很容易混淆。 做了好幾個sample test我纔算是區分清楚。xmlpp::Node是base class. xmlpp::contentNode和xmlpp::Element都繼承於它。xmlpp::Element的概念很容易理解。就是我們平時理解的xml的element,它可以有attribute,也可以有自己的子節點。 libxml++庫裏面xmlpp::contentNode這個名字我覺得取得非常不好, 非常讓我產生誤解。其實它就是指xml裏面的空白以及註釋。 我寫了一個小程序做了驗證。

 

下面這個是example.xml

Makefile 還是用的前一篇文章的。 輸出結果是

root element is "root"
coutent is NULL
node1
coutent is NULL
node2
coutent is NULL

這裏有三個"content is NULL"。  其中第一個是<root>和<node1 a="10">aaaaa</node1>之間的空白

第二個是</node1>和<node2>之間的空白。第三個是</node2>和</root>之間的空白。

爲了驗證我的猜測是正確的, 我將example.xml做了下調整

</node2>後面緊跟</root>。 將之前的換行符刪除。 現在的運行結果是

root element is "root"
coutent is NULL
node1
coutent is NULL
node2

只有兩個"content is NULL"。

 

所以在代碼中 xmlpp::Node::NodeList node_list = pNode -> get_children(); 獲取nodelist後 遍歷每個Node時,將其cast成的ContentNode指針爲空時說明現在找到的是我們需要的Element。 當然這裏也可以cast成Element指針。 當Element指針不爲空時就是我們要找的Element。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章